Reputation: 29
I have a long select tag with lots of options that I need to add PHP script to them. I'm trying to make a JQuery script that will help me do it for all the option tags, but have no idea how. I need jQuery to change this:
<option value="a">A</option>
<option value="b">B</option>
....
<option value="z">Z</option>
to:
<option value="a" <?= isset($array["a"]) ? "selected" : "" ?>>A</option>
<option value="b" <?= isset($array["b"]) ? "selected" : "" ?>>B</option>
....
<option value="z" <?= isset($array["z"]) ? "selected" : "" ?>>Z</option>
How can I achieve this without too much effort? (the list is actually about 200 items long)
I am able to iterate through the list, but I can't seem to add the attributes or whatever.
$(document).ready(function() {
$("#select option").each(function()
{
var attr = " <?= isset($array['."+$(this).attr("value")+"']) ? 'selected' : '' ?>";
///how to add this to the tag??
});
});
Upvotes: 0
Views: 244
Reputation: 2040
Because you just want to generate a php file I would suggest using string/regex replace in your ide/editor
going from
<option value="a">A</option>
to
<option value="a" <?= isset($array["a"]) ? "selected" : "" ?>>A</option>
In vim (but other editors should support this too) you can do this with
:%s/value=\(".*"\)/value=\1 <?= isset($array[\1]) ? "selected" : "" ?>/g
where the part you search for is
value=\(".*"\)
and this is the part you replace
value=\1 <?= isset($array[\1]) ? "selected" : "" ?>
using
\([someregex]\)
you can 'store' some variable and with \1 you can output it in the replace part 1
Upvotes: 0
Reputation:
Making that change with jQuery won't magically execute the stuff in the PHP tags. You have to handle this logic server side.
I suggest writing a PHP script that makes the repetitive changes to the .php
file in question. Either that, or use an editor with regex support to do it for you.
For example, in Notepad++, you could (regex) replace all occurrences of:
(<option value=")([^"]+)(">.+?</option>)
with:
\1\2<?= isset($array["\2"]) ? "selected" : "" ?>\3
Upvotes: 1
Reputation: 22817
Though you should separate concerns and you should not be messing PHP with js, just keep it short:
$('#select').val('<?php echo $valueYouNeed; ?>');
Upvotes: 0