how to NOT send a variable unless something is entered in the field

Discussion in 'JavaScript' started by marcnyc, Jun 27, 2009.

  1. #1
    Hello, I am working with a form which has a lot of text fields which submits some data via POST. I would like some of this data to ONLY be sent if the user actually has entered something in the textfield, and if the user didn't I would like that variable not to even be sent via POST (not even an empty value)... Is this possible somehow?
    Thanks
     
    marcnyc, Jun 27, 2009 IP
  2. JavaScriptBank.com

    JavaScriptBank.com Peon

    Messages:
    141
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #2
    JavaScriptBank.com, Jun 28, 2009 IP
  3. Unni krishnan

    Unni krishnan Peon

    Messages:
    237
    Likes Received:
    9
    Best Answers:
    2
    Trophy Points:
    0
    #3
    This can be done by removing the elements whose value is not entered , from the form, and then submitting the form. The following code helps to do so.

    <html>
    
    <head>
    
    <script>
    
    function validateRemove(eId)
    {
      if(document.getElementById(eId).value=="")
      {
         var t = document.getElementById(eId);
         t.parentNode.removeChild(t);
      }
    }
    
    
    function submitFunc()
    {
       validateRemove('abc');
       validateRemove('bcd');
    
       document.testform.action = "cssExample.html";
       document.testform.submit();
    }
    
    </script>
    
    </head>
    
    <body onload="document.testform.reset();">
    	<form name="testform">
    		<input type="text" name="abc" id="abc" /><br>
    		<input type="text" name="bcd" id="bcd" /><br>
    		<input type="button" onClick="submitFunc();" value="Submit"/>
    	<form>
    </body>
    
    </html>
    Code (markup):
    Hope this helps.
     
    Unni krishnan, Jun 30, 2009 IP
  4. marcnyc

    marcnyc Peon

    Messages:
    70
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Thanks for posting this code, this is very helpful.
    Thanks for taking the time Unni!
     
    marcnyc, Jun 30, 2009 IP