2014-05-09 35 views
0

進出口尋找到這樣做@ JCOC611在這裏做的jQuery更改輸入文字:https://stackoverflow.com/a/5099898/3223200當已經在同一個頁面多種形式單選按鈕的選擇

中,你可以根據單選按鈕選擇文本值改變

誰曾經,我想在同一個頁面上有幾個表單,這個怎麼做?

原代碼是

<input type="text" id="it" value=""> 
<input type="radio" name="hey" value="one"> 
<input type="radio" name="hey" value="two"> 
<input type="radio" name="hey" value="three"> 

<script> 
$(document).ready(function(){ 
    $("input[type=radio]").click(function(){ 
    $("#it").val(this.value); 
    }); 
}); 
</script> 

演示在這裏:http://jsfiddle.net/jcoc611/rhcd2/1/

而且我想是這樣的:

<form action="hello.php" name="form01" method="post"> 
<input type="hidden" name="productid" value="01" /> 
<input type="radio" name="price" value="1000"> 
<input type="radio" name="price" value="2000"> 
<input type="text" id="it" name="pricevalue" value=""> 
</form> 

<form action="hello.php" name="form02" method="post"> 
<input type="hidden" name="productid" value="02" /> 
<input type="radio" name="price" value="6000"> 
<input type="radio" name="price" value="2400"> 
<input type="text" id="it" name="pricevalue" value=""> 
</form> 

<form action="hello.php" name="form03" method="post"> 
<input type="hidden" name="productid" value="03" /> 
<input type="radio" name="price" value="500"> 
<input type="radio" name="price" value="700"> 
<input type="text" id="it" name="pricevalue" value=""> 
</form> 

<script> 
$(document).ready(function(){ 
    $("input[type=radio]").click(function(){ 
    $("#it").val(this.value); 
    }); 
}); 
</script> 

在同一個頁面上使用多個形式,而是利用相同功能

這怎麼辦?

+0

你不應該在相同的id DOM的多個元素。 –

回答

2

用途:

$(document).ready(function() { 
    $("input[type=radio]").click(function() { 
     $(this).closest('form').find("input[type=text]").val(this.value); 
    }); 
}); 

jsFiddle example

通過使用.closest().find()你可以選擇最接近於選擇相對單選按鈕,文本輸入元素。

請注意,ID 必須是唯一的。

0

如果您使用siblings(),代碼少一點。

$(document).ready(function(){ 
    $("input[type=radio]").click(function(){ 
     $(this).siblings("input[type=text]").val(this.value); 
    }); 
}); 

jsFiddle example

相關問題