简体   繁体   中英

How to set the value of a form element using Javascript?

I have a simple form like this one:

<form ENCTYPE="multipart/form-data" action="upload.php" method="POST">
<p>UPLOAD FILE: <input type="file" name="file1"> <br /></p>
<input type="submit" value="Upload">
<input type="hidden" name="email" id="email" value="">
</form>

I have to set the value of the hidden field to an email like "email@email.com". I can obtain this value from adding a querystring parameter by external iframe like:

<iframe name="email@email.com" src="index.html?email=email@email.com">

Ok. But how can I set value="" to value="email@email.com"? I know have to use javascript, but I dunno how to deal with the var.

document.getElementById('Id').value='new value';

answer to comment: try this:

<input type="" name="email" id="email">

<iframe id="frm" name="email@email.com" src="index.html?email=email@email.com">
</iframe>

<script>
document.getElementById('email').value = document.getElementById('frm').name;
</script>

then you can change adopt it. change type to hidden and etc.

If your script is executed from the document inside the iframe, you can do this :

var getUrlParameter = function(name, defaultValue) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( document.location.href );
    if( results == null ) return defaultValue;
    else return decodeURIComponent(results[1]);
};

document.getElementById('email').value=getUrlParameter('email');

As you've labeled this question as jQuery You can use $('#Id').val('new value'); But don't forget to add jQuery Library.

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