2012-07-09 32 views
2

我有一個簡單的形式,像這樣的:如何使用Javascript設置表單元素的值?

<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> 

我不得不隱藏字段的值設置爲郵件像「[email protected]」。 我可以從通過外部的iframe添加查詢字符串參數等獲得此值:

<iframe name="[email protected]" src="[email protected]"> 

確定。但是,我怎樣才能將value =「」設置爲value =「[email protected]」? 我知道必須使用javascript,但我不知道如何處理var。

+0

你也可以填補它在服務器端,如果你想 - 你可以讓你的index.html使用一些服務器端處理,當你生成表單時,接收email參數並將其插入到字段中。但是,使用JavaScript也很容易。 – Rup 2012-07-09 10:46:44

+0

查看[這個問題](http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript)來提取查詢字符串值。有些解決方案可能對您需要的東西有點過分,但它們也很強大。 – Rup 2012-07-09 10:51:53

回答

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

答案評論: 試試這個:

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

<iframe id="frm" name="[email protected]" src="[email protected]"> 
</iframe> 

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

則可以更改採納。更改類型爲隱藏等。

+1

好吧,但這個值是動態的。 我必須從外部iframe的querystring參數中提取它。 這是我的問題:/ – user840718 2012-07-09 10:49:13

+0

@ user840718請參閱更新。 – F0G 2012-07-09 10:56:59

0

正如您已將此問題標記爲jQuery您可以使用$('#Id').val('new value');但請不要忘記添加jQuery Library。

+0

告訴其他用戶該var是動態的。 我不知道我該如何處理val('新值')。 – user840718 2012-07-09 10:51:01

2

如果你的腳本是從iframe中的文件執行的,你可以這樣做:

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'); 
+0

@你是對的。編輯。 – 2012-07-09 10:58:29

+0

好吧,這對我有效。 謝謝。 – user840718 2012-07-09 11:00:39

相關問題