0

Need a little help on this one. I am trying to write jQuery code to change the selection of a select dropdown. Following the excellent advice on here, I am using .val(). However, this doesn't remove the selected attribute, so I am also doing that.

The part where I am stuck is, I want to add the selected attribute to the new option, but the value of the new option (which is stored in the PHP value $option) has double quotation marks in it.

var shopDropdown = $(".buy__option-select__select", 
                   $('iframe')[0].contentWindow.document);
var initialSelection = $(".buy__option-select__select > option[selected]",
                       $('iframe')[0].contentWindow.document);
initialSelection.attr('selected',false); 
$(".buy__option-select__select", 
   $('iframe')[0].contentWindow.document).val('<?php echo $option ?>');
$('.buy__option-select__select > option[value="<?php echo addslashes($option) ?>"]', 
   $('iframe')[0].contentWindow.document).attr('selected',true);
shopDropdown.trigger('change');

Thanks!

2
  • The way you are using JQuery to get all the matches and then return just the first as a standard DOM object, I would just lose the JQuery and use vanilla JavaScript and the DOM. JQuery is way overused in 2020 for trivial tasks that the DOM can handle quite easily. Commented Jul 31, 2020 at 21:54
  • I am open to that suggestion, but I do not know how to accomplish that Commented Jul 31, 2020 at 22:41

2 Answers 2

2

AFAICT you are just trying to select one of the options in your select. You need to use .prop() to do that reliably. There is a note about this in the docs. They are writing about the checked attribute, but a note below says the same applies to selected:

Nevertheless, the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does .... The same is true for other dynamic attributes, such as selected and value.

So once we are using the right method, the only problem to worry about is that pesky quote. We can solve that by carefully arranging double and single quotes.

Working (simplified) JSFidddle

HTML

<form>
    <select name="foo" class="buy__option-select__select">
        <option value=''>Please Choose</option>
        <option value='1'>One</option>
        <option value='two-with-"-quote'>Two</option>
        <option value='3' selected>Three</option>
    </select>
</form>

Javascript

$(document).ready(function () {

    var $select = $('.buy__option-select__select'),
    
        // Now specify the value of the option we want to select.  This
        // obviously must exactly match one of the listed value="x" values
        // above.  Also note that as it includes a double quote, we need
        // to surround it with single quotes.
        // 
        // You would use this PHP like this:
        // var target='<?php echo $option; ?>'
        // For demonstration we use some plain text:
        target = 'two-with-"-quote';    
        
    // Now just carefully arrange our quotes so that we have single quotes
    // surrounding our option:
    $("[value='" + target + "']", $select).prop('selected', true);
});
Sign up to request clarification or add additional context in comments.

4 Comments

There's really no reason to post your code example to a 3rd party site because those links can die over time and make that link unreachable. If you are going to post the code in your answer anyway, just post it as a Stack Snippet.
@ScottMarcus Thanks, I appreciate the suggestion. I am aware of snippets, however they are not as practical for iterative work, trying things and testing, which is what I was using JSFiddle for. Whether or not I include a link to the JSFiddle isn't really relevant as long as the code is here on SO - which is exactly why I included it here, in full. Whether or not it is also is a snippet is a matter of personal preference - and as it is my answer, that's my decision to make. I've rolled your edit back.
It is your answer and you certainly have the right to reverse an edit. But, I wonder if you'll consider that switching to another browser tab, updating code there, saving that code, copying the new URL, coming back to this browser tab, clicking to edit your answer, updating a link, and clicking save is not really more conducive to an iterative approach than just clicking edit right where you are, updating code and then hitting save. Not to mention that anyone who wants to try your code can do it right here without going to another site where the link may or may not work in the future.
@ScottMarcus Thanks for your concern, but the process is neither as taxing as you seem to imagine, nor as awkward.
0

The part where I am stuck is, I want to add the selected attribute to the new option, but the value of the new option (which is stored in the PHP value $option) has double quotation marks in it.

JQuery was revolutionary when it was introduced. It made querying the DOM and performing many operations much simpler. But, in the 14 years since it was introduced the native API for interacting with a document (the Document Object Model) has, in many ways, caught up and now performing many of the tasks JQuery once made easy work of, is just as easy (and often much more simple) if you just use the standard DOM API (a.k.a. "vanilla JavaScript").

If we take that approach here, your selectors become much simpler, with less nesting of quotes in quotes, which eliminates your issue.

Here's your code in vanilla JavaScript without the quote problem:

// Reference the <iframe>
var iFrame = document.querySelector("iframe");

// Reference the <select> in the <iframe>
var shopDropdown = iFrame.contentWindow.document.querySelector(".buy__option-select__select");

// De-select the initially selected <option>
shopDropdown.options[options.selectedIndex].selected = false;

// Set the value for the <select>
shopDropdown.value = "<?php echo $option ?>";

// Set the <option> who's value attribute matches the PHP result to be selected
shopDropdown.querySelector['value="<?php echo addslashes($option) ?>"'].selected = true;

// Trigger the change event on the <select>
shopDropdown.change();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.