Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Neither if nor else is triggering

Here is my statement:

$(document).ready(function() {
    $('#search_option').change(function() {
        alert('changed');
        if( $('#search_option').val() == "wiki" ) {
            $('#search_form').setAttribute('action', "http://www.wikipedia.org/search-redirect.php");
            $('#search_bar').setAttribute('name', "search");
            alert('Got inside wiki');
        } else {
            $('#search_form').setAttribute('action', "http://www.google.com/search");
            $('#search_bar').setAttribute('name', "q");
            alert('Got inside google');
        }
    });
});

Neither of the 'got inside' alerts are triggering, meaning that neither of them are running, correct? I can not seem to figure out why neither parts of the if statement are running, at least one should be

like image 459
Troy Cosentino Avatar asked Dec 13 '22 00:12

Troy Cosentino


2 Answers

setAttribute is a dom element node method use .attr() thats the jQuery method

$(document).ready(function() {
    $('#search_option').change(function() {
        alert('changed');
        if( $('#search_option').val() == "wiki" ) {
            $('#search_form').attr('action', "http://www.wikipedia.org/search-redirect.php");
            $('#search_bar').attr('name', "search");
            alert('Got inside wiki');
        } else {
            $('#search_form').attr('action', "http://www.google.com/search");
            $('#search_bar').attr('name', "q");
            alert('Got inside google');
        }
    });
});

Since setAttribute is not a method of the jQuery object an error is produced and the code stops execution therefore it never reaches the alerts.

like image 108
Musa Avatar answered Dec 15 '22 00:12

Musa


.setAttribute() isn't a valid jQuery method. Use .attr().

$(document).ready(function() {
    $('#search_option').change(function() {
        alert('changed');
        if( $('#search_option').val() == "wiki" ) {
            $('#search_form').attr('action', "http://www.wikipedia.org/search-redirect.php");
            $('#search_bar').attr('name', "search");
            alert('Got inside wiki');
        } else {
            $('#search_form').attr('action', "http://www.google.com/search");
            $('#search_bar').attr('name', "q");
            alert('Got inside google');
        }
    });
});​
like image 37
nbrooks Avatar answered Dec 15 '22 00:12

nbrooks