Select:

Optionally omit the selection option from the form view

Given the shape of HTML, for example:

<html>
<body>
<form method="GET">
    Select:
    <select id="param" name="param">
        <option></option>
        <option value="Value 1">Value 1</option>
        <option value="Value 2">Value 2</option>
        <option value="Value 3">Value 3</option>
    </select>
    <button type="submit">Submit</button>
</form>
</body>
</html>

How can I completely omit a parameter from the form view if an empty parameter is selected?

+4
source share
4 answers

If you need a pure JavaScript approach, something like this will remove the nameelement attribute selectif the selected value optionwas empty before the form was submitted.

Just give the form element a name ..

<form name="formName" method="GET"></form>

JS - EXAMPLE HERE

document.forms["formName"].addEventListener('submit', function(){
    var el = this.querySelector('select[name="param"]');
    if(!el.value){
        el.removeAttribute('name');
    }
});

Alternatively, here is the version of jQuery .. not much different.

EXAMPLE HERE

$('form[name="formName"]').submit(function(e){
    var el = $(this).find('select[name="param"]');
    if(!el.val()){
        el.removeAttr("name");
    }
});
+2
source

This is what I came up with (jQuery):

$("form").submit(function(e) {
  if ($("#param").val() === "")
    $("#param").removeAttr("name");
});

, DOM submit.

+1

, JQuery

<script type="text/javascript">
   function checkForm()
   {
     var paramVal = $('#param').val();
     if(paramVal == "0"){ return false;}
   }
</script>

<select name="param" id="param">
    <option value="0"></option>
    <option value="Value 1">Value 1</option>
    <option value="Value 2">Value 2</option>
    <option value="Value 3">Value 3</option>
</select>
<button type="submit" onclick="return checkForm();">Submit</button>
0
<script type="text/javascript">
   function validate()
   {
 if ($("#param").val() == "")
    $("#param").removeAttr("name");
   }
</script>
<form action="" method="post" onsubmit="return validate()">
<select name="param" id="param">
    <option value=""></option>
    <option value="Value 1">Value 1</option>
    <option value="Value 2">Value 2</option>
    <option value="Value 3">Value 3</option>
</select>
<button type="submit">Submit</button>
</form>
0
source

Source: https://habr.com/ru/post/1531384/


All Articles