简体   繁体   中英

Get the value of an <input type=“text”> that was created dynamically inside a modal

i would like to get the value of an <input type="text"> that was created dynamically inside a modal and put it into variable "newcomment". This is how i make the input:

    var newcomment;
    var p = $("<p>");
    p.append("Some text");
    p.append("</p>");
    p.append("<input type='text'id='comment_text' value='Comment'"+"onblur=newcomment=$('#comment_text').val()"+" onfocus=if(this.value==this.defaultValue)this.value=''>"+"</input>");
    $("div.modal-body").append(p);

The problem is when i write something like "ok" inside the textbox in the modal, and after i focusout from the textbox: newcomment seems not update to "ok" and still have the default "Comment" value.

1st: You need to use newcomment=this.value instead of newcomment=$('#comment_text').val() 2nd: No need to add + signs in your input html code while you not trying to concatenate string by putting variables to it

 var newcomment; var p = $("<p>"); p.append("Some text"); p.append("</p>"); p.append("<input type='text' id='comment_text' value='Comment' onblur='newcomment=this.value; alert(newcomment);' onfocus=if(this.value==this.defaultValue)this.value='' />"); $("body").append(p); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

Not really the answer here, but might help you get at the root of the problem.

JS:

var newComment, defaultValue;

function doOnBlur(){
    newComment = $('#comment_text').val()
}

function doOnFocus(){
    if($('#comment_text').val() == defaultValue){
        $('#comment_text').val('')
    }
}

HTML:

<input type='text' id='comment_text' placeholder='Comment' onblur='doOnBlur()' onfocus='doOnFocus()' /> 
<!-- inputs dont have a close tag, also should use placeholder for temporary text -->

from here, you can set breakpoints in the debugger and see where your code is going wrong. You can also modify the functions much more easily rather than writing the executing code in the HTML

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM