Home > database >  I want to restrict the data sent from the form from appearing in the URL?
I want to restrict the data sent from the form from appearing in the URL?

Time:03-06

I want to restrict the data submitted from the form to appear in the url. If only the word is entered or only the amount is selected, I want that value to come from the url. How can I do it as jquery? For example, there is a construction like the one below, but it doesn't work. Limiting data submitted with jquery form in url? E.g;

<form id="form1" name="form1" method="get" action="">
<input type="text" name="word" >
<input type="number" name="total_amount" >
<select name="amount" >
<option value="15">
<option value="20">
<option value="25">
</select>
<button type="button" id="submit" >
<span >Filter</span>
</button>
</form>

 < script>
$(document).ready(function(){
$('#submit').click(function() {

$('#form1 input[type="text"]').each(function(){   
if(!$(this).val()){
$(this).prop("name","");
}else{
$(this).val("");
}
});

$('#form1 input[type="number"]').each(function(){
    
if(!$(this).val()){
$(this).prop("name","");
}else{
$(this).val();
}
});
       
$('#form1 select').each(function(){    
if(!$(this).val()){
$(this).prop("name","");
}else{
$(this).val();
}
});
});
});   
</ script>

CodePudding user response:

I had started writing a solution before the discussion above ended, so here is that. I am using what appears to be your design goal of $.each() on the elements in the form.

I will show (1) vanilla way to do it with hard-coded form fields, and (2) a more generic way to do it with jQuery. You can use either and its also possible to upgrade the vanilla way to be generic as well.

Whether or not you even use this code (since it's kinda pointless IMHO for your SEO purposes), it will show you or give insights into how you can use javascript to apply conditionals on form data, which comes in handy for other use-cases, such as "validation".

All remaining explanations of this SOLUTION is in the code comments that follow.

// This is the generic jQuery approach of this SOLUTION, and by generic meaning it doesn't matter what the IDs of the
// fields are in the form, just so long as each field to be inspected needs to have an ID.

function validateSubmitJquery() {
    
    var action = "somescript.php"; // your GET fields go after the question mark, but later
    var params = []; // make this an array, we'll convert to string later
        
    $('#form1 input, select').each(function(){  
    console.log( this )
        if ( $(this).val().trim().length  > 0) {
            params.push({
                key: $(this)[0].id, // [0] to get ID from DOM element itself
                value: $(this).val().trim()
            });
        }
    });
    
    console.log(params);
        
    // USe params array to compose the url
    var url = action.toString(); // use toString to clone the action part, tho not really needed here
    
    if (params.length > 0) {
        url  = "?"; // params come after the question mark
        
        for (var i = 0; i < params.length; i  ) {

            if (i > 0) {
                url  = "&"; // each param is separated by ampersand
            }
            
            // add the param key and value to the url. Url encode the value to prevent problems
            
            url  = params[i].key   "="   encodeURIComponent( params[i].value );
    
        }
    }
    
    // Now you have an Url with conditional values based on whatever requirements.
    // So you can redirect to this Url now
    
    // location.href = url; // uncomment to do actual redirection
    
    console.log("URL: "   url);

}



// This concept is written in vanilla with each field being hard coded so it's easy to follow the design 
// strategy here.

function validateSubmitConcept() {
    // var vword = $("#word").val(); // jquery way, uncomment if you want jquery
    var vword = document.getElementById("word").value; // vanilla way, delete this line if you want jquery
    
    // var vnumber = $("#number").val(); // jquery way, uncomment if you want jquery
    var vnumber = document.getElementById("number").value; // vanilla way, delete this line if you want jquery
    
    // var vamount = $("#total_amount").val(); // jquery way
    var vamount = document.getElementById("total_amount").value;
    
    // Since you are using GET parameters, you can compose the URL as a string
    
    var action = "somescript.php"; // your GET fields go after the question mark, but later
    var params = []; // make this an array, we'll convert to string later
    
    if (vword.trim().length > 0) { // use trim to rid trailing and beginning white space
        params.push({
            key: "word",
            value: vword.trim() 
        });
    }
    
    if (vnumber.trim() != "") { 
        params.push({
            key: "number",
            value: vnumber
        });
    }
    
    if (vamount.trim() != "") { 
        params.push({
            key: "total_amount",
            value: vamount
        });
    }
    
    console.log(params);
    
    // USe params array to compose the url
    var url = action.toString(); // use toString to clone the action part, tho not really needed here
    
    if (params.length > 0) {
        url  = "?"; // params come after the question mark
        
        for (var i = 0; i < params.length; i  ) {

            if (i > 0) {
                url  = "&"; // each param is separated by ampersand
            }
            
            // add the param key and value to the url. Url encode the value to prevent problems
            
            url  = params[i].key   "="   encodeURIComponent( params[i].value );
    
        }
    }
    
    // Now you have an Url with conditional values based on whatever requirements.
    // So you can redirect to this Url now
    
    // location.href = url; // uncomment to do actual redirection
    
    console.log("URL: "   url);
    
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

<!-- You don't need a true form in this SOLUTION, except for styling, so lose the method and action -->

<!-- form id="form1" name="form1" method="get" action="" --> 

<form id="form1">
<!-- edit your form fields by replacing the `name` attribute with `id` on the elements inside the form -->

    <input type="text" id="word" >
    <input type="number" id="total_amount" >
    <select id="number" >
    
    <!-- <option> needs closing </option> and optional text in between to show in drop down -->
    
        <option value=""></option> <!-- Blank option for when user selects no number, you can omit this line -->
        <option value="15">15</option>
        <option value="20">20</option>
        <option value="25">25</option>
    </select>
    
    <!-- make a button that has type button so that it doesn't submit -->
    
    <button type="button" onclick="validateSubmitConcept()">Submit (Concept)</button> 
    <button type="button" onclick="validateSubmitJquery()">Submit (jQuery)</button> 
</form>

Basically what the above code does, is gathers the values of the form fields (by ID), applies conditions on what should be included in the URL, in this case any field that is not blank, composes those fields into a valid URL string, then redirects to wherever with those values.

  • Related