0

I have this javascript:

$(function() {

  $("#generate").click(function() {
  $("#id").val(generateID($("#age").val()));
    var increaseBy = increaseBase(generateSOCS());

    $("#numbersoc1").val(increaseBy(0));
    $("#numbersoc2").val(increaseBy(1));
    $("#numbersoc3").val(increaseBy(2));
    $("#numbersoc4").val(increaseBy(3));
  });

  $.getJSON("age.json", function(json) {

        $("#age").empty();
        $("#age").append($('<option>').text("Select age"));

        $.each(json, function(i, obj){
            $("#age").append($('<option>').text(obj.age).attr('value', obj.permanent));
        });
    });
});

function increaseBase(base) {
  return function(value) {
    return "SOCS" + (base + value).toString(16).toUpperCase()
  }
}

function generateSOCS() {
  return random(10, 16777215);
}

function generateID(permanent) {
    if(permanent == "Select age")
        return "Please select your age first!";
        var add = 5
    return (permanent + random(1,100) + random(100,50000) + ++add);
}

function random(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

And this html:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src='script.js'></script>
<h1>Number Generator</h1>

<div>
 <select name="age" id="age"></select><br/>

  <input id="generate" type=button value="Generate" /><br/><br/> 
  <br/>
  Identifier<br/>
   <input id="id" placeholder="Identification Number" /><br/><br/>
  Number<br/>
  <input id="numbersoc1" placeholder="Number Soc. S1." /><br/>
  <input id="numbersoc2" placeholder="Number Soc. S2." /><br/>
  <input id="numbersoc3" placeholder="Number Soc. S3." /><br/>
  <input id="numbersoc4" placeholder="Number Soc. S4." /><br/>
</div>

And this json:

[
    { "age": "18", "permanent": "AA" },
    { "age": "19", "permanent": "BB" },
    { "age": "20", "permanent": "CC" }
]

When I click the 'Generate' button without selecting an age in the drop down menu then the 'Identifier' box will show the following: 'Please select your age first!' which is normal and expected however I would like to do the same thing for the 4 Number boxes. Help would be appreciated.

Also, can the code be made more efficient? By that I mean shorter. If yes how?

Thank you in advance.

Hanuman
  • 27
  • 8
  • please clarify your problem more thoroughly, the numbersoc* inputs all have a placeholder, isn't this what you wanted? do you want a default value instead of a placeholder? – Kevin Kloet Sep 21 '17 at 07:02
  • Yes the placeholders are ok. But if I click the generate button without selecting an age then value will be generated in the 4 boxes when in fact I would like it to show ''Please select your age first!' instead; just like it does with the Identification Number placeholder. – Hanuman Sep 21 '17 at 07:06
  • Can you edit your question and add Code Snippet in it? So that we can regenerate your point and help you. – Nikhil Parmar Sep 21 '17 at 07:11
  • I am trying to add a snippet. I can add the HTML and JS code but not the JSON code. I will try to edit my question hopefully for the best. – Hanuman Sep 21 '17 at 07:13

2 Answers2

2

You should check the value of the selected value in #age first.
This can be achieved with a simple if else statement.

$("#generate").click(function() {
  if ($('#age').val() !== '<your default value>') {
    //your code for setting the values of the #numbersoc* inputs
  } else {
    //code that notifies the user about needing to select an age.
  }
});

Note that for this example it is required to have a default value as an option in your age select tag.
this can be achieved by using the following option tag.

<option selected="true" disabled="disabled">Select your age</option>  

Edit
added the solution into OP's code.

$(function() {
  $("#generate").click(function() {
  //checks if the value of #id is an empty string
    if ($("#id").val(generateID($("#age").val())).val() == '') {
    //alerts the user that they should enter an age
    //feel free to make something nice here
      alert('Please insert age first');
    } else {
    var increaseBy = increaseBase(generateSOCS());

    $("#numbersoc1").val(increaseBy(0));
    $("#numbersoc2").val(increaseBy(1));
    $("#numbersoc3").val(increaseBy(2));
    $("#numbersoc4").val(increaseBy(3));
  }
});

  //uncomment this when using the json
  /*$.getJSON("age.json", function(json) {

    $("#age").empty();
    $("#age").append($('<option>').text('Select age').attr('value', 'Select age')
    .attr('selected', true).prop('disabled','disabled'));

    $.each(json, function(i, obj) {
      $("#age").append($('<option>').text(obj.age).attr('value', obj.permanent));
    });
  });*/
});

function increaseBase(base) {
  return function(value) {
    return "SOCS" + (base + value).toString(16).toUpperCase()
  }
}

function generateSOCS() {
  return random(10, 16777215);
}

function generateID(permanent) {
// simple check for default, empty or null value
  if ($('#age').val() == 'Select age' || $('#age').val() == '' || $('#age').val() == null) {
    return;
  }
  var add = 5
  return (permanent + random(1, 100) + random(100, 50000) + ++add);
}

function random(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src='script.js'></script>

<h1>Number Generator</h1>

<div>
  <select name="age" id="age">
  <!-- the options will be auto generated -->
    <option selected="true" disabled="disabled">Select age</option>
    <option>1</option>
    <option>2</option>
    <option>3</option>
  </select>
  <br/>

  <input id="generate" type=button value="Generate" />
  <br/>
  <br/>
  <br/> Identifier
  <br/>
  <input id="id" placeholder="Identification Number" />
  <br/>
  <br/> Number
  <br/>
  <input id="numbersoc1" placeholder="Number Soc. S1." />
  <br/>
  <input id="numbersoc2" placeholder="Number Soc. S2." />
  <br/>
  <input id="numbersoc3" placeholder="Number Soc. S3." />
  <br/>
  <input id="numbersoc4" placeholder="Number Soc. S4." />
  <br/>
</div>
Kevin Kloet
  • 1,086
  • 1
  • 11
  • 21
  • This looks like the proposed solution below but either I'm doing something wrong or there is a problem in the code. Mind including your proposal in my code? Thank you. – Hanuman Sep 21 '17 at 08:49
  • @Hanuman sorry for the late response, I have added a snippet with the solution in your code, note that I commented the json reading function and made option tags myself – Kevin Kloet Sep 21 '17 at 10:05
  • Thanks Kevin. Highly appreciated. – Hanuman Sep 21 '17 at 10:18
  • Not sure if I understood well but when uncommenting the json it does not work. I get an `TypeError: undefined is not an object (evaluating '$(' – Hanuman Sep 21 '17 at 10:27
  • @Hanuman I made a small mistake by using prop for the selected attribute and there were missing quotes, should be fixed now – Kevin Kloet Sep 21 '17 at 10:42
  • Thanks Kevin. All works as intended now. I appreciate the help and time. – Hanuman Sep 21 '17 at 10:45
1

You just have to check like you did within generateRandom(), like this:

$(function() {

      $("#generate").click(function() {
      if($("#age").val() !== 'Select age'){
      $("#id").val(generateID($("#age").val()));
        var increaseBy = increaseBase(generateSOCS());

        $("#numbersoc1").val(increaseBy(0));
        $("#numbersoc2").val(increaseBy(1));
        $("#numbersoc3").val(increaseBy(2));
        $("#numbersoc4").val(increaseBy(3));
       }else{
             $("#id").val('Please select an age');
        var errMessage = 'Please select your age';
            if(!$("#numbersoc1").val())
                $("#numbersoc1").val(errMessage)
            if(!$("#numbersoc2").val())
                $("#numbersoc2").val(errMessage)
            if(!$("#numbersoc3").val())
                $("#numbersoc3").val(errMessage)
            if(!$("#numbersoc4").val())
                $("#numbersoc4").val(errMessage)
        }
      });

      $.getJSON("age.json", function(json) {

            $("#age").empty();
            $("#age").append($('<option>').text("Select age"));

            $.each(json, function(i, obj){
                $("#age").append($('<option>').text(obj.age).attr('value', obj.permanent));
            });
        });
    });

    function increaseBase(base) {
      return function(value) {
        return "SOCS" + (base + value).toString(16).toUpperCase()
      }
    }

    function generateSOCS() {
      return random(10, 16777215);
    }

    function generateID(permanent) {
              var add = 5
return (permanent + random(1,100) + random(100,50000) + ++add);
    }

    function random(min, max) {
      min = Math.ceil(min);
      max = Math.floor(max);
      return Math.floor(Math.random() * (max - min + 1)) + min;
    }
Eladian
  • 958
  • 10
  • 29
  • This does not seem to work. When no age is selected it does the same thing as my original code. When an age is selected now the code is broken and I get a `can't find variable: permanent` error. – Hanuman Sep 21 '17 at 08:47
  • wait what did you want it to do when no age is selected? – Eladian Sep 21 '17 at 08:49
  • I have fixed the permenent undefined error, If you could explain more on what you would like it to do when no value is selected that would be sweet – Eladian Sep 21 '17 at 08:51
  • To simply say in the 4 boxes numbersoc1, numbersoc2, numbersoc3 and numbersoc4 'Please select your age first!' as it is already doing in the id placeholder. – Hanuman Sep 21 '17 at 08:52
  • Still not working after the fix. 'Please select your age first!' is not showing in the numbersoc1, numbersoc2, numbersoc3 and numbersoc4 boxes when no age is selected and the Generate button pushed. – Hanuman Sep 21 '17 at 08:55
  • I'm aware of that, I'm unsure of how you want this done though because the user may put something in numbersoc1 and numbersoc 2 and then click generate, do you want to replace their input values with 'Please select you age first' or would you like it to display somewhere else so you don't override their current values? – Eladian Sep 21 '17 at 08:56
  • Those boxes (numbersoc1,2,3,4) are meant for the user to see the generated values when the user selects and age and then clicks the Generate button. All I need is for those boxes to show 'Please select your age first!' if the user pushes the Generate button but has not selected any age first. Your last edit kind of worked but only for the first placeholder numbersoc1. The other 3 are not showing it. Also if there is a value in either of the boxes then 'Please select your age first!' will not show if the user clicks generate and an age has not been selected. – Hanuman Sep 21 '17 at 09:06
  • Thanks @Eladian. It works fine and as intended. Thanks for your help and time. – Hanuman Sep 22 '17 at 03:49