2013-12-08 26 views
1

我試圖在文本字段中生成一個隨機數。不幸的是ID在這裏不是一個選項,所以我使用類作爲標識符。我嘗試了很多東西,但似乎無法得到這項工作。使用javascript/jQuery將文本輸入生成隨機數

HTML輸入:

<div class="productAttributeRow productAttributeConfigurableEntryNumbersOnlyText"> 
    <div class="productAttributeLabel"> 
     <label> 
      <span class="name"> 
       Hidden: 
      </span> 
     </label> 
    </div> 
    <div class="productAttributeValue"> 
     <input type="text" class="Field validation" value="" size="5" /> 
    </div> 
</div> 

我曾嘗試:

var randomnumber = Math.floor(Math.random() * 11) 
$('#BuyThis').click(function() { 
    $(".productAttributeConfigurableEntryNumbersOnlyText.productAttributeValue input[type=" 
    text "]").val(randomnumber); 
}); 

在上述情況下,#BuyThis一個按鈕:

<a id="BuyThis" type="button" class="btn btn-small btn-warning" href="#product-options" data-toggle="modal"> 

然而,這種情況發生,沒有必要點擊一下,我只需要在表單提交之前在該字段中輸入一個隨機數字。

也試過沒有點擊:

$(function(){ 
    var randomnumber=Math.floor(Math.random()*11)  
    $('.productAttributeConfigurableEntryNumbersOnlyText.productAttributeValue input[type="text"]').val(randomnumber);  

}) 

的另一種嘗試:

function randomNumber(m, n) { 
    m = parseInt(m); 
    n = parseInt(n); 
    randomnumber = Math.floor(Math.random() * (n - m + 1)) + m; 
    ('.productAttributeConfigurableEntryNumbersOnlyText.productAttributeValue input[type="text"]').value = randomnumber; 
}); 

嘗試各種其他功能和組合都無濟於事。

+0

你可以提供您的問題的演示。? –

回答

3

productAttributeValue類的div裏面productAttributeConfigurableEntryNumbersOnlyText,所以選擇時,你應該在它們之間添加一個空格:

$(function(){ 
    var randomnumber=Math.floor(Math.random()*11)  
    $('.productAttributeConfigurableEntryNumbersOnlyText .productAttributeValue input[type="text"]').val(randomnumber);  
}); 

是否工作:http://jsfiddle.net/3hhCx/

+0

哈哈哈......我大概看了六次,卻在同一時間做了一百萬件事,並一直忘記去做。咄!謝謝你,謝謝你,謝謝你,非常感謝你。我一直在努力工作的時間比我應有的時間要長很多,看到它工作起來非常放心。謝謝! 〜蘇珊 – susan

2
$('.productAttributeConfigurableEntryNumbersOnlyText.productAttributeValue') 

是選擇具有兩個元素.productAttributeConfigurableEntryNumbersOnlyText.productAttributeValue

你想選擇一個具有.productAttributeValue的元素,它是.productAttributeConfigurableEntryNumbersOnlyText的子元素。

要做到這一點,添加一個空格之間:

$('.productAttributeConfigurableEntryNumbersOnlyText .productAttributeValue') 

插入隨機值,使用:

var randomnumber=Math.floor(Math.random()*11)  
$('.productAttributeConfigurableEntryNumbersOnlyText .productAttributeValue input[type="text"]').val(randomnumber); 
1

試試這個... HTML

<div class="productAttributeRow productAttributeConfigurableEntryNumbersOnlyText"> 
    <div class="productAttributeLabel"> 
     <label> 
      <span class="name"> 
       Hidden: 
      </span> 
     </label> 
    </div> 
    <div class="productAttributeValue"> 
     <input type="text" class="Field validation" value="" size="5" /> 
    </div> 

javascript:

var randomnumber=Math.floor(Math.random()*11)  

$('#BuyThis').click(function(){  
    $(".productAttributeConfigurableEntryNumbersOnlyText .productAttributeValue input:text").val(randomnumber); 
}); 

嘗試Demo