2014-10-05 72 views
-1

我有这样的表行中表获取输入的值之后,DIV是点击

<tr> 
    <th> 
     <input type="text" id="ismall" maxlength="2" size="2" placeholder="0"> 
    </th> 
    <th> 
     <input type="text" id="imedium" maxlength="2" size="2" placeholder="0"> 
    </th> 
    <th> 
     <input type="text" id="ilarge" maxlength="2" size="2" placeholder="0"> 
    </th> 
    <th> 
     <input type="text" id="ixlarge" maxlength="2" size="2" placeholder="0"> 
    </th> 
    </tr> 
    <tr> 
     <th colspan="4" style="padding: 0px"> 
     <div class="add-to-cart" onclick="addToCart()">Add to pizza cart</div> 
    </th> 
    </tr> 
</tr> 

当我点击add-to-cart我会提醒什么是ismallimediumilargeixlarge里面的数据。但我无法使用JavaScript获得价值。

我该怎么办?

的JavaScript

function addToCart(){ 
    alert(document.getElementById('ismall').value); 
} 
+0

div ??你为什么不使用按钮? – 2014-10-05 07:59:15

+0

@BhaveshGangani让我可以更容易地设计风格。 – 2014-10-05 08:00:47

+0

你也可以设计风格的按钮。为了达到这种目的,推荐使用一个按钮。 – 2014-10-05 08:07:54

回答

0

代码的工作是正确的。但是,您应该使用​​函数将字符串转换为数字值。例如,

function addToCart(){ 
    alert(Number(document.getElementById('ismall').value)); 
} 

HTML +的Javascript fiddle here

我建议你把你的javascript放在页面的底部而不是<head>标签。例如。在关闭</body>标记之前放入javascript。

0

我建议你使用按钮进行点击,但无论如何这不是问题。此外,我再次建议你到addEventListener的事件。您的JavaScript

document.getElementsByClassName('add-to-cart')[0].addEventListener('click', function() { 
    alert(document.getElementById('ismall').value); 
}) 

http://jsfiddle.net/0w3j94sf/1/

这样的作品,但你的代码,我想也应该是工作。你的输入中有一个占位符,女巫是0.而这不是一个值。如果您单击该按钮并且未设置输入值,则警报结果将为空。如果您不想具有默认值,则必须在输入上设置属性value="0"

0

它工作正常,检查我的小提琴

Js Fiddle

function addToCart() { 

    a = document.getElementById('ismall').value 
    b = document.getElementById('imedium').value 
    c = document.getElementById('ilarge').value 
    d = document.getElementById('ixlarge').value 

    alert(a + ' ' + b + ' ' + c + ' ' + d); 
} 

如果字段为空,它会给空白警报

0

试试这个live DEMO

<form id=pizzaForm > 
     <tr> 
     <th> 
      <input type="text" id="ismall" maxlength="2" size="2" placeholder="0" autofocus required> 
     </th> 
     <th> 
      <input type="text" id="imedium" maxlength="2" size="2" placeholder="0" required> 
     </th> 
     <th> 
      <input type="text" id="ilarge" maxlength="2" size="2" placeholder="0" required> 
     </th> 
     <th> 
      <input type="text" id="ixlarge" maxlength="2" size="2" placeholder="0" required> 
     </th> 
     </tr> 
     <tr> 
      <th colspan="4" style="padding: 0px"> 
      <input type="submit" value="Add to pizza cart" id="continue_btn" class="add-to-cart"/> 
     </th> 
     </tr> 
    </tr> 
</form> 

的js

function addToCart(){ 
    allIput.forEach(function(e){ 
     alert(e.value); 
    }); 
} 

var allIput =Array.prototype.slice.call(document.querySelectorAll("input[type=text]")), 
highlightForm = document.querySelector("#pizzaForm"); 

highlightForm.addEventListener('submit',addToCart , false);