I'm trying to check if a form input has any value (doesn't matter what the value is) so that I can append the value to the action URL on submit if it does exist. I need to add the name of the param before adding the value, and just leaving a blank param name like "P=" without any value messes up the page.
Here's my code:
function getParam() {
// reset url in case there were any previous params inputted
document.form.action = 'http://www.domain.com'
if (document.getElementById('p').value == 1) {
document.form.action += 'P=' + document.getElementById('p').value;
}
if (document.getElementbyId('q').value == 1) {
document.form.action += 'Q=' + document.getElementById('q').value;
}
}
and the form:
<form name="form" id="form" method="post" action="">
<input type="text" id="p" value="">
<input type="text" id="q" value="">
<input type="submit" value="Update" onClick="getParam();">
</form>
I thought setting value == 1 would do a开发者_开发技巧 simple exists, doesn't exist check regardless of what the submitted value was, but I guess I'm wrong.
Also, I'm using if statements, but I believe that's bad code, since I don't have an else. Perhaps, using a switch statement, though I'm not sure how I would set that up. Perhaps:
switch(value) {
case document.getElementById('p').value == 1 :
document.form.action += 'P=' + document.getElementById('p').value; :
case document.getElementById('q').value == 1 :
document.form.action += 'Q=' + document.getElementById('q').value; break;
}
var val = document.getElementById('p').value;
if (/^\s*$/.test(val)){
//value is either empty or contains whitespace characters
//do not append the value
}
else{
//code for appending the value to url
}
P.S.: Its better than checking against value.length
because ' '.length
= 3.
精彩评论