Jump to content

Recommended Posts

I have a form with 6 <select> options. All <select> filed will have same values but with different names. Like this:

<form action="" method="post">
<select name="var1" class="form-control">
<option value="0">0</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
<option value="100">100</option>
</select>

<select name="var2" class="form-control">
<option value="0">0</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
<input type="submit" name="submit" value="Submit"/>
</form>
 <?php
if(isset($_POST['submit']))
{
    include ('connect.php') ;
include('admin_auth.php');
    $var1 = $_POST['var1'];
    $var2 = $_POST['var2'];
    
     $var3= $_POST['var3'];
// till $var6
    
$var11 = (mt_rand(1,3));
$var12 = rand(4,6);
$var13 = mt_rand(1,6);

// Here i should get only those variables n values which are greater than 0
}

I am submitting these information to the same page, But before submit is it possible to filter those variables which are greater than 0? I want to POST only those variables which has value greater than 0. How can i do it?

 

In the same page, i want to compare these values with the 3 random numbers which will generate when submit button is clicked.

 

I tried doing like this using like this

<script>
  var form = document.querySelector("form");
    form.addEventListener("submit", function(e) {
      e.preventDefault();
      var data = new FormData();
      var selects = e.target.querySelectorAll(".form-control");
      var values = [];
      for (var i = 0; i < selects.length; i++) {
        // if `select` `.value` is not `0`,
        // add to `values` array`
        if (selects[i].value != 0) {
          values.push([selects[i].name, selects[i].value])
        };       
      };
      // if `values` array contains items
      // append items to `FormData` object
      if (values.length) {
      values.forEach(function(val) {
        data.append(val[0], val[1])
         alert(val[0]);
      })
      var request = new XMLHttpRequest();
      request.open("POST", "/echo/js/")
      request.onload = function() {
        values = [];
        console.log(data);
        // log values posted
        for (prop of [...data]) {
          console.log(prop)
        }
      }
      request.send(data)
    
      }
    });
</script>

But nothing is happening, i tried to debug with Firebug, it shows

TypeError: form is null

form.addEventListener('submit', function(evt) {

Can somebody help me in this?

 

 

 

 

For some reason

var form = document.querySelector("form");
isn't doing what you think it should - var form is null on the next line. obviously you can't assign an event to a null element.

 

I would suspect giving the actual form a name (or at the very least an ID) would go some ways to helping you out of this specific issue.

<script type="text/javascript">
  $('#addnameform').on('submit', function(e){
e.preventDefault();
    
      var data = new FormData();
      var selects = e.target.querySelectorAll(".form-control");
      var values = [];
      for (var i = 0; i < selects.length; i++) {
        if (selects[i].value != 0) {
          values.push([selects[i].name, selects[i].value])
        };       
      };
      if (values.length) {
      values.forEach(function(val) {
        data.append(val[0], val[1], val[2], val[3], val[4], val[6])
        alert(val[0]);        
      })
      var request = new XMLHttpRequest();
      request.open("POST", "/echo/js/")
      request.onload = function() {
        values = [];
        console.log(data);
                
        for(prop of[...data]) {
          console.log(prop)
        
        }
      }
      request.send(data)
            
      }
    });
</script>

is it right?

now am not getting that error, but nothing is the output

If you have jQuery linked it should look something a little bit like this:

$('#addformName').on('submit', function(e){
  e.preventDefault();
  var selectVals =[];
  $('#addformName select').each(function(idx, elm){
    if(elm.val() > 0){
      selectVals[idx] = elm.val();
    }
  })
  if (selectVals.length() >= 1){
  $.ajax({
    method: 'POST',
    url: 'path/to/page.php',
    data: selectVals,
    success: function(data){
      alert(data);
    }
  })
});

That's likely not going to work as is, and the ajax definitely won't because the url is nonsense, but it covers the core of what you are trying to do.

Edited by Muddy_Funster

Is there a reason you are trying to do this in Javascript rather than the PHP file you're posting to? It'd be easier in PHP, especially if you convert the inputs to an array.

<form action="" method="post">
<select name="var[]" class="form-control">
<option value="0">0</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
<option value="100">100</option>
</select>

<select name="var[]" class="form-control">
<option value="0">0</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
<input type="submit" name="submit" value="Submit"/>
</form>
$var = array_filter($_POST['var']);
//Now $var only contains non-zero entries.
If you really want to use Javascript then the easiest thing to do would probably be to disable the inputs with 0 values and use jquery to serialize the form.

 

$('#formId').submit(function(e){
   e.preventDefault();
   var form = $(this);
   var selects = form.find('select');

   //Disable zero values.
   selects.each(function(idx,ele){
      if (ele.value == 0) ele.disabled=true;
   });
   
   //Gather form data
   var data = form.serialize();

   //Re-enable selects
   selects.prop('disabled', false);

   $.post('script.php', data);
});
Something like that.
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.