How to check if input value matters

I am trying to check if the form input has any value (it doesn't matter what value) so that I can add the value to the action URL to submit, if it exists. I need to add a parameter name before adding a value and just leave an empty parameter name, for example "P =", without any value it will interfere with the page.

Here is 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 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 that setting == 1 would make it simple, there is no verification, no matter what the value was, but I think I'm wrong.

In addition, I use if statements, but I think the code is bad, since I have no other. Perhaps using a switch statement, although I'm not sure how I will set this up. Maybe:

 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; } 
+6
javascript conditional forms
source share
1 answer
 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 } 

PS: Better than checking for value.length because ' '.length = 3.

+13
source share

All Articles