【问题标题】:jQuery - How do I add one to a variable when an input is entered?jQuery - 输入输入时如何向变量添加一个?
【发布时间】:2017-08-24 19:04:32
【问题描述】:

代码如下:

	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"});
	}
<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>

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

例如,当你回答“你叫什么名字”时,它应该将风险表从 0 变为 1。

【问题讨论】:

  • 如何运行代码?它需要在事件监听器中,以便在用户输入内容时运行。
  • 能否请您包含您的html?不过,您问题的核心是您只在加载时运行此代码。
  • 是否应该为输入中的每个字符增加风险变量?
  • 我包含了 html。它应该增加整个输入而不是每个字符的风险变量。

标签: jquery html input


【解决方案1】:

你必须在你的输入中添加一个事件监听器。

var risk = 0;

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

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

【讨论】:

    猜你喜欢
    • 2016-04-27
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 2016-01-23
    • 2021-06-15
    • 1970-01-01
    相关资源
    最近更新 更多