0

This is my code for html

 <div id="content"></div> 

Then I append an inpunt to #content:

 $( document ).ready(function() {
  // Handler for .ready() called.
       var parameter = "<p>Hola</p>";
       $("#content").append('<div><p>click the button</p>'+
                     '<input type="submit" name="submit_answers" value="Submit" onclick="getValue();" >'+  
                     '<input type="submit" name="submit_answers" value="Submit" onclick="'+getValue2(parameter)+'" >'+                        
                     '</div>');
});

function getValue2(parameter){
    alert(parameter);
}

function getValue(){
    alert("Hola");
}

The first input works very well, but the second input dosen´t work after document is ready. What´s the better way to declare a function in this case?

5 Answers 5

6

You can try this:

'<input type="submit" name="submit_answers" value="Submit" onclick="getValue2(\'' + parameter + '\');" >'
Sign up to request clarification or add additional context in comments.

Comments

2

You could do this:

onclick="getValue2("' + parameter + '")"

But something like this would be better:

var $div = $('<div><p>click the botton</p></div>');
var $button = $('<input type="submit" name="submit_answers" value="Submit">')
    .data('parameter', parameter)
    .click(function () {
        getValue2($(this).data('parameter'));
    }).appendTo($div);

$("#content").append($div);

Comments

1

Try this :

$( document ).ready(function() {
// Handler for .ready() called.
   var parameter = "<p>Hola new</p>";
   $("#content").append('<div><p>click the botton</p>'+
                 '<input type="submit" name="submit_answers" value="Submit" onclick="getValue();" >'+  
                 '<input type="submit" name="submit_answers" value="Submit" onclick="getValue2(\''+parameter+'\');" >'+                        
                 '</div>');
});

Comments

1

I think you probably just weren't separating correctly.

Try this example :

onclick= "mySup(\''+json.id+'\',\''+json.description+'\');"

Comments

0

The second input should be something like that.

'<input type="submit" name="submit_answers" value="Submit" onclick="getValue2('+parameter+')" >'

1 Comment

yes! it works only for numeric parameters. To solve the problem also for strings you will need to put the parameter variable between apostrophes "getValue2("'+parameter+'")".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.