Member Avatar for diafol

Hi All,

Just to say that I've searched DW and Google extensively before posting here. Also looked at the jQuery site, but failed to find exactly what I'm looking for. Anyway here's the thing:

I have a button on a form, that when it's pressed inserts some new inputs (textboxes) to the form. Then another button should copy the contents of the first of these inputs to all the others. Now, this is tricky, js tells me that these inputs are undefined, presumably as they are added after page load. I've looked at .bind(), .delegate(), .live() and .on(), but can't see how to interact these inputs.

Here's the form:

<form id="numbers" method="post" action="anotherpage.php">
    <label for="numinputs">No. Inputs to Add: </label> <input id="numinputs" type="number" min="1" max="6" value="1" /> <button id="addinputs">Add Inputs</button><br />
    <button id="sync" style="display:none;">Sync All To First</button><br />
    <input type="submit" value="Upload" name="submit" id="submit" />
</form>

So just an input and button to send the number of textboxes to add. Here's the preliminary jQ/js:

//this just extends to allow .repeat method
String.prototype.repeat = function(num) {
    return new Array(isNaN(num)? 1 : ++num).join(this);
}
//this works - it adds the corerct number of textboxes to the form
function addInputs(){
    var str = '<label>MyNumber</label> <input class="numbertexbox" type="number" min="1" max = "20" value="7" /><br />';
    var numToAdd = parseInt($('#numinputs').val());
    $('#sync').before(str.repeat(numToAdd));
}
//this works - it calls the functions to add textboxes and shows the sync button
$('#numinputs').click(function(e){
    e.preventDefault();
    $('#sync').show();
    addInputs();        
});

//this breaks - $('.numbertextbox') is undefined 
$('#sync').click(function(e){
    e.preventDefault();
    $('.numbertextbox').val('15');
});

So, question is, how can I interact with all the newly added $('.numbertextbox') textboxes?

Recommended Answers

All 2 Replies

Hi diafol,
It was a typo:

function addInputs(){
    var str = '<label>MyNumber</label> <input class="numbertexbox" type="number" min="1" max = "20" value="7" /><br />';
    var numToAdd = parseInt($('#numinputs').val());
    $('#sync').before(str.repeat(numToAdd));
}

please check the class name in the input element. It has a missing 't' in 'text'.

$('#sync').click(function(e){
    e.preventDefault();
    // This one has 't'
    $('.numbertextbox').val('15');
});
commented: hangs head in shame -thanks +14
Member Avatar for diafol

I don't believe it! t-thanks gon1387! I've been at it for hours and for the life of me, I couldn't understand it. Serves me right - I never use class names that long - now I remember why. Big hand gon.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.