JQuery selector for parameter tag value attribute returns null

I am trying to change a selected option in a dropdown list using jQuery. I set it so that it finds a hash tag at the end of the URL and based on this hash tag it changes the selected option in the selection box.

Most of my code works, it successfully finds the hash tag and executes the if statement corresponding to it. However, when it proceeds to execute the "then" section of the instruction, when it proceeds to the selector for the parameter (which uses the attribute selector based on the value attribute of the option tag), it returns null. If you figure this out with firebug, the console says the selector is null.

Here is my code:

$(document).ready(function() {
    var $hash = window.location.hash
    if($hash == "#htmlcss") {
    $('option[value="HTML/CSS Coding"]').attr("selected","selected")
    }
    if($hash == "#php") {
    $('option[value="PHP Coding"]').attr("selected","selected")
    }
    if($hash == "#jscript") {
    $('option[value="Javascript and jQuery Coding"]').attr("selected","selected")
    }
    if($hash == "#improv") {
    $('option[value="General Website Improvements"]').attr("selected","selected")
    }
    if($hash == "#towp") {
    $('option[value="Website Conversion to Wordpress"]').attr("selected","selected")
    }
    if($hash == "#wptheme") {
    $('option[value="Wordpress Theme Design"]').attr("selected","selected")
    }
    if($hash == "#complete") {
    $('option[value="Complete Website Creation"]').attr("selected","selected")
    }
    if($hash == "#server") {
    $('option[value="Web Server Configuration"]').attr("selected","selected")
    }
});

, , URL-, #php, , , "PHP Coding" , "", html, null. , ? .

+3
4

, .val() :

var hashmap  = { 
  htmlcss: "HTML/CSS Coding",
  php: "PHP Coding",
  jscript: "Javascript and jQuery Coding",
  improv: "General Website Improvements",
  towp: "Website Conversion to Wordpress",
  wptheme: "Wordpress Theme Design",
  complete: "Complete Website Creation",
  server: "Web Server Configuration"
};

$(function() {
    var $hash = window.location.hash.replace('#','');
    $("#IDOfSelectElement").val(hashmap[$hash]);
});

<select> ( ID) .val(), <option> , , , . , , , , value="", <option>... , value="". , , :)

+5

, , , :

$('option[value=HTML\\/CSS Coding]').attr("selected","selected")

. http://api.jquery.com/category/selectors/

+1

, if:

$('option').removeAttr('selected');

, select, .

0
source

Why not assign an identifier to each choice? This will make your code tidier.

$(document).ready(function() {
   $(window.location.hash).attr("selected","selected");
});
0
source

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


All Articles