简体   繁体   中英

JQuery update select option

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!

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);
});

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 (aka "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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM