我试图根据来自单选按钮和文本的输入使JS输出全名。我有一个问题,因为我希望它输出这个人的选择,但每当我点击男性或女性时,它总是显示为男性(加上文字)。我目前输出的代码是:
window.onload = initAll;
function initAll() {
document.getElementById("sillySubmit").onclick = function() {
document.getElementById("msgField").innerHTML = getSillyName();
return false;
}
}
function getSillyName() {
var x = $('input[id]').click(function() {
($('input[id]:checked').val());
});
var lastName1 = ["lots of names"];
var lastName2 = ["lots more names" ];
var lastNm = document.getElementById("lName").value.toUpperCase();
var validName = true;
if (lastNm == "") {
validName = false;
}
else {
var lastNum1 = lastNm.charCodeAt(0) - 65;
var lastNum2 = lastNm.charCodeAt((lastNm.length-1)) - 65;
if (lastNum1 < 0 || lastNum1 > 25 || lastNum2 < 0 || lastNum2 > 25) {
validName = false;
}
}
if (!validName) {
document.getElementById("lName").focus();
document.getElementById("lName").select();
return "I say. Something gone a bit squiffy here. Try again...";
}
return "Your name is " + x + ' ' + lastName1[lastNum1] + ' '
+ lastName2[lastNum2]; //add in comparisons later on
}
其中&#39; x&#39;代表男性和&#39; y是女性。我可以添加/更改哪些内容以显示正确的首选项?
答案 0 :(得分:0)
我可以添加/更改哪些内容以显示正确的首选项?
如果我理解正确,答案将是:括号。
代码将变为:
"Your name is " + (x || y) + ' ' + lastName1[lastNum1] + ' ' + lastName2[lastNum2];
答案 1 :(得分:0)
尝试在返回值之前定义名字。
if(gender == 'male')
firstname = ...
else
firstName = ...
return 'Your name is ' + firstname + ' ' + lastName1[lastNum1] + ' ' + lastName2[lastNum2];
我希望有所帮助。
答案 2 :(得分:0)
我看不到你的HTML,所以我必须猜测很多。我假设你有很多输入元素,都有id属性,你的女/男按钮是其中两个。这些按钮的值为“开”或“关”,在某些浏览器中,它总是“打开”。所以不要寻找价值。其他单选按钮的属性checked
可以是 true 或 false 。
您无需附加点击处理程序即可获取状态。
因此getSillyName()的第一行可能如下所示:
function getSillyName() {
var x;
if (document.getElementById(/* female id here */).checked) {
x = 'Mrs.' // change string to whatever you want to see
} else if (document.getElementById(/* male id here */).checked) {
x = 'Mr.' // as above
} else x = 'cat'; // possibly both are unchecked
/* the very important next line in your code should be: */
console.log(x);
/* this important line move step by step further down your code */
console.log(/* and put in here what you want to check */);
/* rest of code here */
}
之后,您的元素 #msgField 应该显示一些内容。