如果输入名称是值

时间:2014-01-19 00:22:32

标签: javascript jquery forms

这是我的设置:

HTML

1. How are you?
<input class="calc" type="radio" name="1" value="2">Good
<input class="calc" type="radio" name="1" value="1">Okey
<input class="calc" type="radio" name="1" value="0">Bad

的Javascript

 if ( name 1 has value 2)
  { do something }
 else if ( name 1 has value 1)
  { do something }
else if ( name 1 has value 0)
  { do something }
else
  { }

如何使用名称和值制作if else语句?

3 个答案:

答案 0 :(得分:3)

var names = document.getElementsByName("1");

if (names[0].checked)
  { do something }
 else if (names[1].checked)
  { do something }
else if (names[2].checked)
  { do something }
else
  { }

虽然抓住已选中的一个并将其值放在switch()语句中似乎更简单。

var chkd = document.querySelector(".calc:checked");

switch( chkd.value) {
   case 2: // ...
           break;
   case 1: // 
           break;
   default: // ...
}

:checked需要一个现代浏览器,如IE9或更高版本。

答案 1 :(得分:2)

if声明背后的一般前提是:

if ('statement to evaluate') {
    // Code to execute if above statement is true
} else if ('another statement')
    // Code executes if first statement was false, but second one is true
} else {
    // If both above statements are false, execute this code
}

详细了解if statments:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else

有关评估为真的内容的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript

答案 2 :(得分:0)

这是一个完整的例子。最好的部分是 - 你根本不需要条件。您可以使用值本身来确定要使用的回调。此方法称为“属性查找”。

<强> Live demo (click).

示例加价:

<form id="myForm">
  <h3>1. How are you?</h3>
  <input name="1" type="radio" value="2">
  <label>Good</label>

  <input name="1" type="radio" value="1">
  <label>Okay</label>

  <input name="1" type="radio" value="0">
  <label>Bad</label>

  <button disabled>Click me.</button>
</form>

<强> JavaScript的:

var inputs = document.querySelectorAll('#myForm input');

var submit = document.querySelector('#myForm button');

for (var i=0; i<inputs.length; ++i) {
  inputs[i].addEventListener('click', function() {
    submit.removeAttribute('disabled');
  });
}

var responses = [
  function() { //this is "responses[0]
    console.log('this handles value 1!');
  },
  function() { //this is "responses[1]
    console.log('this handles value 2!');
  },
  function() { //this is "responses[2]
    console.log('this handles value 3!');
  }
];

submit.addEventListener('click', function(e) {
  var checked = document.querySelector("#myForm input:checked");
  var x = checked.value;
  responses[x](); //call the response function for this value
  e.preventDefault(); //prevent the form from submitting
});