2013-12-08 29 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