Question

<div id="inputs" style="margin:0;"></div>

$('#addtpcs').change(function() {
  var selectedValue = $(this).val();

  var targetDiv = $("#inputs").html("");
  var a=1;
  for(var i = 0; i < selectedValue; i++) {
     targetDiv.append($("<dd><label for=\"addtpcs\" class=\"label\">Additional PC "+a+"</label><input id=\"addtpcs"+a+"\" type=\"text\"/></dd>"));
    a++;
  }
});

I have a select box (named addtpcs) in a form that has already loaded on the page that has numbers in it (ie. 1,2,3,4, etc) in a form. The above code works great for dynamically added input type=text boxes based upon the number chosen in the select box. However it doesn't work so well for after you click the submit button and then use your back button. The select box shows the number but the text inputs don't load without having to click the drop down select menu and choose and different number and then click on it again and choose the previous number.

I would like it if the back button in the browser was pushed that the value would be looked at on the form and the text boxes would appear based on the value in the select box.

In Jquery how would I check what the value is on page load and on change without writing the code twice?

Thanks,

Wayne

Update I have code that checks a checkbox already on the form if the back button is selected. I am looking for something similar for the select box. The below code upon hitting the back button will check to see if the checkbox is checked and then if it is it will show the two hidden text boxes that are in the form.

$(function() {
if ($("#prevcredit").is(':checked')){
    $("#credit_amount").show();
    $("#credit_amount2").show();
}
else {
     $('#credit_amount2').val('0.00');
}
});
Was it helpful?

Solution

Okay I resolved this.

Step 1: HTML Portion of the code:

<div id="inputs" style="margin:0;"></div>

Step 2: Javascript Function

Create a function in javaScript that appends to the targetDiv. This function will take 1 argument. This will be the value of how many boxes need to be added.

function displayTextBoxes(value)
{
a=1;
targetDiv = $("#inputs").html("");
for(var i = 0; i < value; i++) {
     targetDiv.append($("<dd><label for=\"addtpcs\" class=\"label\">Additional PC "+a+"</label><input id=\"addtpcs"+a+"\" type=\"text\"/></dd>"));
    a++;
  }
}

Step 3: Create the JQuery function calls

The first function looks at the value of whatever is associated with id addtpcs. This will take care of looking at the value when the user pushes the back button in the browser. The second looks to see if the value has changed while you are on the form.

$(function() {
var selectValue = $('#addtpcs').val();
displayTextBoxes(selectValue);
});

$('#addtpcs').change(function() {
  var selectedValue = $(this).val();
  displayTextBoxes(selectedValue);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top