John Cargo
John Cargo

Reputation: 2121

Changing value of variable onclick

I am trying to change variable value on click, so that i can send the value via ajax to load data in ascending or descending format.

Here is Javascript part on top of page.

var ascending = '0';

Here is HTML Part.

<span onclick="knowFormat(true)"><input type="checkbox" id="ascending" name="ascending"><label for="ascending"><i class="fa fa-sort-alpha-asc"></i>&nbsp;Ascending</label></span>

<span onclick="knowFormat(false)"><input type="checkbox" id="descending" name="ascending"><label for="descending"><i class="fa fa-sort-alpha-desc"></i>&nbsp;Descending</label></span>

<span><input type="button" name="sort" onclick="sorting()"></span>

Here is my CSS :

input { display:none; }
input:checked ~ label { color:red; }

Here is my Javascript just before ajax function and after html, css part:

function knowFormat(ascending) {
    if (ascending) { ascending = '0'; } else { ascending = '1'; }
}

And in my Ajax, Data is always getting sent '0', even after click.

function sorting() {
alert(ascending);
    jQuery.ajax({
        url : 'ajax/file.php',
        type : 'POST',
        data : 'ascending='+ascending,
        success : function(s) {
            alert(s);
        }
    });
}

Even after clicking sorting, The alert button is always 0.

Upvotes: 1

Views: 1150

Answers (1)

Adil
Adil

Reputation: 148130

You are changing the parameter due to scope. The same parameter name hides the global variable. To change global variable change the name of parameter or global variable.

function knowFormat(ascending1) {
    if (ascending1) { ascending = '0'; } else { ascending = '1'; }
}

Upvotes: 2

Related Questions