jQuery - 如何在输入输入时向变量添加一个?

时间:2017-08-24 19:04:32

标签: jquery html input

代码如下:



	var risk = 0;

if ($('input').val()) {
	risk += 1 ;
}

	if (risk <= 2) {
		$("#riskAssess").append("LOW RISK").css({"color": "green", "font-size": "25px"});
	} 

	else if (risk <= 4) {
		$("#riskAssess").append("MODERATE RISK").css({"color": "yellow", "font-size": "25px"});
	}

	else {
		$("#riskAssess").append("HIGH RISK").css({"color": "red", "font-size": "25px"});
	}
&#13;
<div id="q2">
			<h2>Answer the Following:</h2>
			<div class="grouping"><p><label for="Name">What is your name?</label></p><input type="text" name="Name"/></div>
			<p>Select your age range.</p>
				<div id="age">
				<label for="U13">Under 13</label> <input class="check" type="checkbox" id="U13" name="U13" />
				<label for="13-17">13-17</label> <input class="check" type="checkbox" id="13-17" name="13-17" />
				<label for="18-25">18-25</label> <input class="check" type="checkbox" id="18-25" name="18-25" />
				<label for="26-34">26-34</label> <input class="check" type="checkbox" id="26-34" name="26-34" />
				<label for="35-54">35-54</label> <input class="check" type="checkbox" id="35-54" name="35-54" />
				<label for="55-64">13-17</label> <input class="check" type="checkbox" id="55-64" name="55-64" />
				<label for="64+">Over 64</label> <input class="check" type="checkbox" id="64+" name="64+" />
				</div>
				
			<div class="grouping"><p><label for="Occupation">What is your occupation?</label></p><input type="text" name="Occupation"/></div>
			<div class="grouping"><p><label for="City">What city do you live in?</label></p><input type="text" name="City"/></div>
			<div class="grouping"><p id="placeofbirth"><label for="pob">Where were you born?</label></p><input type="text" name="pob"/></div>
			<div id="button2"><button id="finish">Finish</button></div>
			
		</div>
		
		<div id="qfinal">
			<h2>You are at a <span id="riskAssess"></span></h2>
&#13;
&#13;
&#13;

它应该为每个输入添加一个。现在它保持不变。

例如,当您回答&#34;您的名字是什么&#34;时,它应该将风险从0更改为1.

1 个答案:

答案 0 :(得分:0)

您必须在输入中添加事件列表器。

var risk = 0;

$('input').focusout(function(){
  risk++;
  encraseRisk();
});

function encraseRisk(){
  console.log(risk);
  // do something with risk
}