Nick
Nick

Reputation: 61

How can I call a jquery function on selecting a dropdown option for dynamically created inputs?

So this is what the page looks like currently:

enter image description here

The first one is hardcoded in and then the rest are added/removed by the buttons. The first one can also be added and removed from the buttons. I want to call a jquery function when the dropdown is changed to change the type from textbox/radiobutton (and text)/checkbox (and text) etc.

Currently it only works on the first Question/Answer and only works if it is the original and not dynamically created. I'm not sure why that is.

Here is how the Q/A's are created and removed

$("#addButton").click(function () {

    if (counter > max_fields) {
        alert("Only " + max_fields + " Questions allowed");
        return false;
    }

    var newTextBoxDiv = $(document.createElement('div'))
         .attr("id", 'TextBoxDiv' + counter);

    newTextBoxDiv.after().html('<label>Question #' + counter + ' : </label>' +
          '<input type="text" name="textbox' + counter +
          '" id="questionbox' + counter + '" value="" />' +
          ' <select id="choice'+ counter +'"><option>Type</option><option>Radio Button</option><option>Text Box</option><option>Check Box</option></select>' +
          '<button id = "remove' + counter + '">Remove</button>' +
          '<br/><label>Answer #' + counter + ' : </label>' +
          '<div id="Answers' + counter + '">' +
          'Option 1: <input type="text" id="answerbox' + counter +
          '1" name="answerbox' + counter + '" value="" />' +
          '<br/>Option 2: <input type="text" id="answerbox' + counter +
          '2" name="answerbox' + counter + '" value="" />' +
          '<br/>Option 3: <input type="text" id="answerbox' + counter +
          '3" name="answerbox' + counter + '" value="" />' +
          '<br/>Option 4: <input type="text" id="answerbox' + counter +
          '4" name="answerbox' + counter + '" value="" /></div>');

    newTextBoxDiv.appendTo("#TextBoxesGroup");
    counter++;
});

$("#removeButton").click(function () {
    if (counter == 1) {
        alert("No more textbox to remove");
        return false;
    }
    counter--;
    $("#TextBoxDiv" + counter).remove();
});

This is how I tried to get it to change types

$('#choice1').change(function () {
    var selected_item = $(this).val()
    var searchEles = document.getElementById("Answers1").children;
    alert(searchEles.length);
    for(var i = 0; i < searchEles.length; i++) {
        $('#answerbox1' + i).attr('type', selected_item);
        //alert(searchEles.length);
    }

});

The web page code is as follows

<input type='button' value='Add Question' id='addButton'/>
<input type='button' value='Remove Question' id='removeButton'/>
<div id='TextBoxesGroup'>
    <div id="TextBoxDiv1">
        <label>Question #1 : </label>
        <input type='text' id='questionbox1'/> 
        <select id="choice1" onchange="$('#choice').val('id');"> //this on change was added and currently does nothing it seems.
            <option value="">Type</option>
            <option value="radio">Radio Button</option>
            <option value="text">Text Box</option>
            <option value="checkbox">Check Box</option>
        </select>
        <button id="remove1">Remove</button>
        <br/><label>Answer #1 : </label>
        <div id="Answers1">
            Option 1: <input type="text" id='answerbox11' name='answerbox1'  value="" />
            <br/>Option 2: <input type="text" id='answerbox12' name='answerbox1'  value="" />
            <br/>Option 3: <input type="text" id='answerbox13' name='answerbox1'  value="" />
            <br/>Option 4: <input type="text" id='answerbox14' name='answerbox1'  value="" />
        </div>
    </div>
</div>

I tried to do something like onchange and then get the ID and go from there but that didn't work. I know it doesn't match the back end jquery name.

TL;DR

  1. I don't know how to dynamically write the jQuery function to work for all of them.
  2. I don't know why even if I hardcode it to #choice1 it will work when its first created but not if i remove and add it even though it has the same exact values. I think it might MAYBE have to do with for loop, because the alert doesn't even trigger the second time around.

Upvotes: 0

Views: 1867

Answers (5)

Ec_
Ec_

Reputation: 66

You could try

$(document).on("change", ".selector", function(){
  //do something

});

//Edit

Add to the select element class for example select-option and a tag that will hold the select's counter

//JS    
...'<select id="choice'+counter+'" class="select-option" number="'+counter+'">'...

and then your on change function would look something like

$(document).on("change", ".select-option", function(){
  //do something
  var selected_type = $(this).attr('value');
  var ans_number = $(this).attr('number');
  $("#answerbox"+ans_number).children('input').attr('type', selected_type);
});

I hope this will help :)

Upvotes: 1

Alfian Busyro
Alfian Busyro

Reputation: 2340

  • First

    <select id="choice1" onchange="$('#choice').val('id');"> //this on change was added and currently does nothing it seems.
    

    This is one reason your never be called. If you bind an event listener to an element, you should not write the actual JS code inside the element.

  • Second

    Bind your listener like this:

$('#choice1').on("change", function () {
    var selected_item = $(this).val()
    var searchEles = document.getElementById("Answers1").children;
    alert(searchEles.length);
    for(var i = 0; i < searchEles.length; i++) {
        $('#answerbox1' + i).attr('type', selected_item);
        //alert(searchEles.length);
    }

});

Upvotes: 0

Chris Caviness
Chris Caviness

Reputation: 586

When elements will be aded dynamically, best practice is to delegate the handler(s). Put your handler on the containing div or window/document .

Upvotes: 0

Bharat Ranpariya
Bharat Ranpariya

Reputation: 1253

If element is dynamic then Jquery will not bind directly as

$('#choice1').change(function (){});

But for that you need to call same function with some static element. For Ex:

 $(".listingDiv").find('#choice1').change(function (){});

or

$(document).find('#choice1').change(function (){});

and it will work. try it.

Upvotes: 0

Jaykumar Patil
Jaykumar Patil

Reputation: 359

For dynamically added elements use

$(selector).on("change", callback)

Upvotes: 0

Related Questions