views:

194

answers:

1

Hi, 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;
}
+3  A: 
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.

N 1.1
This seems to work opposite. When I leave the field blank it appends P= with no value (since it's blank) and when I type something in, it doesn't append anything.
George
:) you are supposed to append when `if` clause evaluates to `false`
N 1.1
Why not just invert the if, since one branch will be empty?, e.g. `if (!/^\s*$/.test(val)) { //...`
CMS
ahh, lol. I misunderstood what you were testing for. I thought you were testing for any character (which is basically what CMS is saying) vs empty or whitespace characters (which you clearly stated, doh!). thanks a lot.And just as a follow up question, is it bad practice to have if statements with no else?
George
@CMS: _The above code is just for explaining purpose._ :)
N 1.1
@George: Use whatever pleases you, personally i use switch very less.
N 1.1