Using print_media_templates i add some settings into wordpress gallery creator that allow me to chose gallery shortcode output (default gallery, masonry, slider) based on additional shortcode parameters.
My code so far :
<?php
add_action('print_media_templates', function(){ ?>
<script type="text/html" id="tmpl-custom-gallery-setting">
<label class="setting">
<span>Gallery Type</span>
<select name="type" data-setting="type" onchange="getval(this);">
<option value="default">Default</option>
<option value="masonry">Masonry</option>
<option value="slider">Slider</option>
</select>
</label>
<div id="slider-settings">
<label class="setting">
<span>Animation</span>
<select id="gallery-type" name="animation" data-settings="animation">
<option value=""></option>
<option value="fade">Fade</option>
<option value="slide">Slide</option>
</select>
</label>
</div>
</script>
<script>
jQuery(document).ready(function() {
wp.media.view.Settings.Gallery = wp.media.view.Settings.Gallery.extend({
template: function(view){
return wp.media.template('gallery-settings')(view)
+ wp.media.template('custom-gallery-setting')(view);
}
});
});
</script>
<?php
});
?>
It's only small part as example since there's much more options to each gallery type. Since there's lot of options i want to display only one corresponding to selected gallery type. In this example i want to display #slider-settings only when #gallery-type select value == "slider".
As for checking select value i found this code:
<script>
function getval(sel) {
if (sel.value == "slider") {
alert(sel.value);
}
}
</script>
with return selected type value (along with onchange="" on #gallery-type select) and display it if it's set to "slider".
But when i want to hide #slider-settings like :
function getval(sel) {
if (sel.value != "slider") {
$('#slider-settings').hide();
}
}
it's not hiding at all.
You have to handle native update function. Update function is fired for each label when a single change is made. (media-views.js line 7232)
var oldUpdate = wp.media.view.Settings.Gallery.prototype.update;
wp.media.view.Settings.Gallery.prototype.update = function(key) {
if( key === "type" ) {
var value = this.model.get( key );
if ( value === "slider" ) {
setTimeout(function(){
jQuery("#slider-settings").css({"display":"block"});
});
} else {
setTimeout(function(){
jQuery("#slider-settings").css({"display":"none"});
});
}
}
// Initialize native code.
oldUpdate.apply(this, arguments);
};
Somehow i managed to get it work by hiding #slider-settings using not jQuery but javascript :
<script>
function getval(sel) {
if (sel.value != "slider") {
document.getElementById('slider-settings').style.display = 'none';
} else {
document.getElementById('slider-settings').style.display = 'block';
}
}
</script>
But to get value it's has to change (since it's onselect=) so first time i display settings it's not hiding. And as i searched there's seems to be not anything like onload= i can use with .
Or is there a way to just reselect it on load ?
I want to disable the drop down options based on the condition. I want to disable all the other options except the option which has the text "Java".
Ex:
<select id="ddlList">
<option value="csharp">C#</option>
<option value="vb">VB.NET</option>
<option value="jquery">jQuery</option>
<option value="java">Java</option>
</select>
In this case Only java option should be enable and others should be disable.
JQuery :
$('#ddlList option:not([value=java])').prop('disabled', true);
JSFiddle
JavaScript :
var filter = document.querySelectorAll('#ddlList option:not([value=java])')
Object.keys(filter).forEach( function(g){ filter[g].disabled = true })
JSFiddle
function optionDisable(selectId, optionIndex){
document.getElementById(selectId).children[optionIndex].disabled="disabled";
}
or
document.getElementById(optionid).style.display = 'none';
or
function makeDisable(){
var a=document.getElementById("ddllist")
a.disabled=true
}
Use the disabled property.
$("#ddlList option[value!='java']").prop("disabled", true);
If you want more control, in a more practical way, you can go over each option:
$("#ddlList option").each(function () {
var allowed = ["java"];
if (allowed.indexOf($(this).val()) === -1) {
$(this).prop("disabled", true);
}
});
You can write your code like this:
Select Language: <select id="ddlList">
<option value="csharp">C#</option>
<option value="vb">VB.NET</option>
<option value="jquery">jQuery</option>
<option value="java">Java</option>
</select>
JavaScript:
$(document).ready(function(){
var condition = true;
if(condition)
{
$("select option").prop('disabled',true);
$("select option[value='java']").removeAttr('disabled');
$("select").val("java")
}
else
{
//apply your logic here
}
});
Demo Fiddle
$("#ddlList option").each(function(){
if(!$(this).val().contains("java"))
$(this).attr('disabled', true);
});
This code lets you set the disabled attribute of each dropdown option by checking if its value contains "java"
JSFIDDLE DEMO
I'm having a problem with filtering HTML select options witch are based html input. For example:
If i write t-shirt in my input i want to see only T-shirts in my select options
My code looks like this...
<input type="text" name="search" id="inputdata" onkeyup="filter()">
<select name="select[]" id="filtersimilar" multiple>
<?php foreach ($all as $row) { ?>
<option value="<?php echo $row->id_product; ?>" itemid="<?php echo $row->name; ?>"><?php echo $row->name; ?></option>
<?php } ?>
</select>
And JS / Jquery code is:
<script>
function filter(){
inp = $('#inputdata').val();
$("#filtersimilar").change(function() {
var options = $(this).data('options').filter('[itemid=' + inp + ']');
$('#select2').html(options);
});
}
</script>
Have you checked jquery.filter documentation? (http://api.jquery.com/filter/) As #Elfentech pointed out, your referring to something that does not exist (options).
I recommend you make all options invisible with "style="display:none;", and when you do the filtering give the filtered options a "display:block;". But still, your filter method looks really out of standard. Check the documentation to understand how filtering works.
Right answer for me was this one
$(function() {
var opts = $('#filtersimilar option').map(function(){
return [[this.value, $(this).text()]];
});
$('#inputdata').keyup(function(){
var rxp = new RegExp($('#inputdata').val(), 'i');
var optlist = $('#filtersimilar').empty();
opts.each(function(){
if (rxp.test(this[1])) {
optlist.append($('<option/>').attr('value', this[0]).text(this[1]));
}
});
});
});
I am appending some HTML elements to the page dynamically. There can be multiple items added and can be added a different times...so it is hard to use a "bind".
I decided to use an inline function---but this does not work on Firefox...works on all other browsers. Notice the onClick for the options. Also, I have tried onblur, onchange, and on select. None of these work with Firefox.
My goal is to have these functions run when the option is selected. I guess I am just missing something.
$("#billTasks").find('tr')
.append('<td><fieldset><select>
<option class="fixedRate" onClick="fixedOption(this)" id="billFixedSelect" value="1">Fixed Rate</option>
<option class="hourly" onClick="hourlyOption(this)" id="billHourlySelect" value="2"></option>
</select>
<input type="text" placeholder="Rate" class="fieldWidth100 rate currency" style="margin-right:10px;"/>
<select class="schedule">
<?php while($row = $db->sql_fetchrow($result)){
echo "<option value=\'{$row['schedule']}\'>{$row['schedule']}</option>\\n";}?>
</select></fieldset></td>');
This is the code in question (in the append string)
<select>
<option class="fixedRate" onClick="fixedOption(this)" id="billFixedSelect" value="1">Fixed Rate</option>
<option class="hourly" onClick="hourlyOption(this)" id="billHourlySelect" value="2"></option></select>
Why Inline You try some thing like this.
$("#billTasks").find('select').live("change", function() {
var SelectedValue = $(this).val();
if (SelectedValue == '1') {
//your task
}
if (SelectedValue == '2') {
//Your Task
}
});
You can use delegate event handler for that:
$('#billTasks ').on('change', 'select', function() {
// your code
hourlyOption(this); // here this points to select itself
});
Read here
I would recommend using a class for this. What you could do is something like this:
function Option(html, events) {
var o = $(html);
for(var k in events) {
o.bind(k, events[k]);
}
return o;
}
Use this something like this:
var o = new Option('<option>blah</option>', { click: function() { } ... });
and o is just a new jquery object. So you can use it anyway.
I have the following HTML <select> element:
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Using a JavaScript function with the leaveCode number as a parameter, how do I select the appropriate option in the list?
You can use this function:
function selectElement(id, valueToSelect) {
let element = document.getElementById(id);
element.value = valueToSelect;
}
selectElement('leaveCode', '11');
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Optionally if you want to trigger onchange event also, you can use :
element.dispatchEvent(new Event('change'))
If you are using jQuery you can also do this:
$('#leaveCode').val('14');
This will select the <option> with the value of 14.
With plain Javascript, this can also be achieved with two Document methods:
With document.querySelector, you can select an element based on a CSS selector:
document.querySelector('#leaveCode').value = '14'
Using the more established approach with document.getElementById(), that will, as the name of the function implies, let you select an element based on its id:
document.getElementById('leaveCode').value = '14'
You can run the below code snipped to see these methods and the jQuery function in action:
const jQueryFunction = () => {
$('#leaveCode').val('14');
}
const querySelectorFunction = () => {
document.querySelector('#leaveCode').value = '14'
}
const getElementByIdFunction = () => {
document.getElementById('leaveCode').value='14'
}
input {
display:block;
margin: 10px;
padding: 10px
}
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
<input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" />
<input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" />
<input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
function setSelectValue (id, val) {
document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);
Not answering the question, but you can also select by index, where i is the index of the item you wish to select:
var formObj = document.getElementById('myForm');
formObj.leaveCode[i].selected = true;
You can also loop through the items to select by display value with a loop:
for (var i = 0, len < formObj.leaveCode.length; i < len; i++)
if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;
I compared the different methods:
Comparison of the different ways on how to set a value of a select with JS or jQuery
code:
$(function() {
var oldT = new Date().getTime();
var element = document.getElementById('myId');
element.value = 4;
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId option").filter(function() {
return $(this).attr('value') == 4;
}).attr('selected', true);
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId").val("4");
console.error(new Date().getTime() - oldT);
});
Output on a select with ~4000 elements:
1 ms
58 ms
612 ms
With Firefox 10. Note: The only reason I did this test, was because jQuery performed super poorly on our list with ~2000 entries (they had longer texts between the options).
We had roughly 2 s delay after a val()
Note as well: I am setting value depending on the real value, not the text value.
document.getElementById('leaveCode').value = '10';
That should set the selection to "Annual Leave"
I tried the above JavaScript/jQuery-based solutions, such as:
$("#leaveCode").val("14");
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
in an AngularJS app, where there was a required <select> element.
None of them works, because the AngularJS form validation is not fired. Although the right option was selected (and is displayed in the form), the input remained invalid (ng-pristine and ng-invalid classes still present).
To force the AngularJS validation, call jQuery change() after selecting an option:
$("#leaveCode").val("14").change();
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
$(leaveCode).change();
Short
This is size improvement of William answer
leaveCode.value = '14';
leaveCode.value = '14';
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
The easiest way if you need to:
1) Click a button which defines select option
2) Go to another page, where select option is
3) Have that option value selected on another page
1) your button links (say, on home page)
<a onclick="location.href='contact.php?option=1';" style="cursor:pointer;">Sales</a>
<a onclick="location.href='contact.php?option=2';" style="cursor:pointer;">IT</a>
(where contact.php is your page with select options. Note the page url has ?option=1 or 2)
2) put this code on your second page (my case contact.php)
<?
if (isset($_GET['option']) && $_GET['option'] != "") {
$pg = $_GET['option'];
} ?>
3) make the option value selected, depending on the button clicked
<select>
<option value="Sales" <? if ($pg == '1') { echo "selected"; } ?> >Sales</option>
<option value="IT" <? if ($pg == '2') { echo "selected"; } ?> >IT</option>
</select>
.. and so on.
So this is an easy way of passing the value to another page (with select option list) through GET in url. No forms, no IDs.. just 3 steps and it works perfect.
function foo(value)
{
var e = document.getElementById('leaveCode');
if(e) e.value = value;
}
Suppose your form is named form1:
function selectValue(val)
{
var lc = document.form1.leaveCode;
for (i=0; i<lc.length; i++)
{
if (lc.options[i].value == val)
{
lc.selectedIndex = i;
return;
}
}
}
Should be something along these lines:
function setValue(inVal){
var dl = document.getElementById('leaveCode');
var el =0;
for (var i=0; i<dl.options.length; i++){
if (dl.options[i].value == inVal){
el=i;
break;
}
}
dl.selectedIndex = el;
}
Why not add a variable for the element's Id and make it a reusable function?
function SelectElement(selectElementId, valueToSelect)
{
var element = document.getElementById(selectElementId);
element.value = valueToSelect;
}
Most of the code mentioned here didn't worked for me!
At last, this worked
window.addEventListener is important, otherwise, your JS code will run before values are fetched in the Options
window.addEventListener("load", function () {
// Selecting Element with ID - leaveCode //
var formObj = document.getElementById('leaveCode');
// Setting option as selected
let len;
for (let i = 0, len = formObj.length; i < len; i++){
if (formObj[i].value == '<value to show in Select>')
formObj.options[i].selected = true;
}
});
Hope, this helps!
You most likely want this:
$("._statusDDL").val('2');
OR
$('select').prop('selectedIndex', 3);
If using PHP you could try something like this:
$value = '11';
$first = '';
$second = '';
$third = '';
$fourth = '';
switch($value) {
case '10' :
$first = 'selected';
break;
case '11' :
$second = 'selected';
break;
case '14' :
$third = 'selected';
break;
case '17' :
$fourth = 'selected';
break;
}
echo'
<select id="leaveCode" name="leaveCode">
<option value="10" '. $first .'>Annual Leave</option>
<option value="11" '. $second .'>Medical Leave</option>
<option value="14" '. $third .'>Long Service</option>
<option value="17" '. $fourth .'>Leave Without Pay</option>
</select>';
I'm afraid I'm unable to test this at the moment, but in the past, I believe I had to give each option tag an ID, and then I did something like:
document.getElementById("optionID").select();
If that doesn't work, maybe it'll get you closer to a solution :P