I've got three dropdown menu's which are dynamically filled from the database each time I select an option in the previous dropdown menu.
Now I want to access the values in these dropdown menu's, so that I can build a SQL-query somewhere later.
I've used the following code to access the HTML elements:
$( window ).load(function(){
var e = document.getElementById("slctTable");
var slctTableValue = e.value;
console.log(slctTableValue);
});
This code only works the first time the page loads, so when I mess around with the dropdown menu's, nothing changes.
What I want now, is that each time I select a value in the dropdown menu, it updates the slctTableValue variable.
Bind change event to the drop-down with jquery, then this event will fire whenever there is a change happened on the selected value.
$("#slctTable").change(function() {
var slctTableValue = $(this).val();
console.log(slctTableValue);
});
You can detect change event like this and update value:
document.getElementById('slctTable').addEventListener('change',function(){
var e = document.getElementById("slctTable");
var slctTableValue = e.value;
console.log(slctTableValue);
});
Related
In a Wordpress installation I have a custom post type and a metabox with custom post_meta fields.
Parent dropdown field in Gutenberg's sidebar used to be a <select> element. I have some scripts that onChange trigger the hide/show of different fields making them conditional, depending whether the page being edited is a parent or child:
$(document).on("change", ".editor-page-attributes__parent select", function(){
toggleFields();
}
The options in the <select> have IDs as values so I could get Title and ID for the selected parent and dynamically show some data in the metabox for my user:
var dropdown = $('.editor-page-attributes__parent select');
var parentName = dropdown.find(':selected').text();
var parentId = dropdown.val();
Since v5.6 Wordpress has replaced that select element with a Combo Box. I have tried to get the same data onChange and only had some success using blur:
$(document).on("blur", ".editor-page-attributes__parent .components-combobox-control__input", function(){
toggleFields();
var parentName = dropdown.val();
})
I was only able to get the page title since this combobox now has an input element that's missing IDs, like this one:
<input id="components-form-token-input-0" type="text" class="components-combobox-control__input components-form-token-field__input" value="Page Name Here">
I have also tried doing an Ajax, to retrieve the ID using get_page_by_title() but it does not always work because pages might have the same title and editor also adds dashes and spaces in names for hierarchy levels.
How can I get the associated ID of the page selected in the Parent Combobox on change?
After some time reading the Editor Documentation I found the proper solution. This is how you can listen to changes and get the id of the Parent Combobox select in the WP Editor:
wp.data.subscribe( function () {
var newParent = wp.data.select('core/editor').getEditedPostAttribute('parent');
console.log(newParent);
} );
wp.data.subscribe is called every single time a change occurs in the current state while editing posts in the editor, so the listener function is called every single time. We can avoid that with a simple variable check when there is an actual change to the field we want. It behaves as Redux subscribe without unsubscribe and only one listener.
To also check for the current post type we are editing we can use getCurrentPostType:
wp.data.select('core/editor').getCurrentPostType();
This is the full code for this problem for future reference:
if (wp.data.select('core/editor').getCurrentPostType() == 'cpt_name') {
const getPostParent = () => wp.data.select('core/editor').getEditedPostAttribute('parent');
// set initial parent
let postParent = getPostParent();
wp.data.subscribe(() => {
// get current parent
const newPostParent = getPostParent();
// only if parent changes
if( postParent !== newPostParent ) {
// Do what we want after parent changed
toggleFields();
}
// update the variable
postParent = newPostParent;
});
}
I have a form where the user can dynamically add or remove sets of fields. For each set of fields, when the user enters/changes a value in the upc[] text input I want to make an Ajax query and populate the corresponding desc[] text input. I can capture the change event, but have not been able to read or modify the dynamically create desc[] field:
This snippet does not have the Ajax call as for now I just want to know I can set desc[x].val(). I have tried to associate the dynamic field with a parent element that existed when the DOM was created...but still no luck.
$(document).on('change', '.upcScan', function(){
var upcIdx = $(this).index('.upcScan');
var upcVal = $(this).val();
alert ("The current index is "+upcIdx+" and the value is "+upcVal);
var descName = "desc["+upcIdx+"]";
var descVal = $("#addClient input[name='"+descName+"']").val();
alert("desc field is "+descName+" and value is "+descVal);
});
The code above returns null. If I try to set the val nothing happens.
What am I missing?
I want to get the selected value from a dropdown box.
Then I want to use that value to change the background-image.
The two code snippits I think are useful:
document.observe("dom:loaded",function(){
initialize();
addTextboxes();
var sel = document.getElementById("select");
for(i = 0; i < pieces.length; i++) {
pieces[i].observe("click",function(event){
moveThis(event.toElement.innerHTML-1);
});
pieces[i].style.backgroundImage = sel.value;
}
var e = document.getElementById("select");
alert(e.options[e.selectedIndex].value);
var value = document.getElementById("select").value;
alert(value);
});
function addTextboxes(){
var sel = document.createElement("select");
//Add the options
sel.options[sel.options.length] = new Option("text0","url(luigi1.jpg)");
sel.options[sel.options.length] = new Option("text1","url(luigi2.jpg)");
sel.options[sel.options.length] = new Option("text2","url(luigi3.jpg)");
sel.options[sel.options.length] = new Option("text3","url(luigi4.jpg)");
//add the element to the form
document.getElementById("overall").appendChild(sel);
}
I have already put two alerts in it to test if something happens, but they don't even show up.
Also, when I place the forloop in the addTextboxes() function, then it changes the background to the first selected option, but doesn't change when you change the box.
I see a few things that need to be changed in your code.
You can't use getElementById("select") without giving an element the select id. Ids are different from tag types, and must be unique throughout your whole page. In the fiddle below, I'm using 'mySelect' for this, to avoid confusion.
You shouldn't listen for a click event on each option. Instead, you should listen for the change event on the entire select element. After a change, the value of the select element will be the value of the option that was chosen.
Here's a fiddle with these changes
After making those changes, the value of chosen option is now displayed in an alert box.
From here, you'd be able to change the background image, or do anything else.
With the use of jQuery its simply this line here
$( "#selectbox option:selected" ).text();
That will get the text of the selected option, you could always get the value using this method:
$( "#selectbox option:selected" ).val();
I have a select option box that is dynamically populated, so if I change the select some other boxes are filled, and I can delete them too.
Which also deletes the option from the select box, this works fine, but when I delete the options and I have just one left in the box, there seem to be no way to fire the option.
$("#email_name").on("change", function(){
var componentkeys = myDailyemail.getKeys($("#Component").val());
$.each(componentkeys, function(kIndex, kItem) {
$("#key").append($("<option/>").val(kItem).text(kItem.toUpperCase()));
});
});
You can automatically trigger a change event after you populated the select element, making it as if the user already selected the first option.
$("#email_name").on("change", function(){
var componentkeys = myDailyemail.getKeys($("#Component").val());
$.each(componentkeys, function(kIndex, kItem) {
$("#key").append($("<option/>").val(kItem).text(kItem.toUpperCase()));
});
$("#key").trigger("change"); // trigger key
}).trigger("change"); // trigger email_name
I wasn't sure what you wanted to trigger so I entered both possibilities.
You can use .trigger() to fire events manually.
Insert following, where needed.
$("#email_name").trigger('change');
I have a dropdown select list on my page of class="TypeFilter".
I have a jQuery event that fires when a value in that list is selected.
$(".TypeFilter").change(function()
{
// Extract value from TypeFilter and update page accordingly
));
I now have to add another list to the page, and I want to implement functionality which will prevent the .change(function() from running unless both are selected.
In both lists the first option in the list is some text instructing the user to select one of the items, so I was thinking of just writing some logic to test that both lists have a selected index greater than 0.
I think this is a touch unclean though, especially considering that other pages that have a TypeFilter use the same logic.
Is there any nifty functionality in jQuery that can do this?
edit I should specify that the user needs to be able to update the page by selecting either dropdown, so I can't put the onchange on the second element and test that the first element has a selected value, as suggested in one of the answers
If you bind the same event to all dropdowns, you can get a collection of all the dropdowns and check that all of them are selected. Example:
$('.Dropdown').change(function(){
var elements = $('.Dropdown');
if (
elements.filter(function(){
return this.selectedIndex > 0;
}).length == elements.length
) {
// all dropdowns are selected
}
});
As you partly mention, put the onchange on the second element and test that the first element has a selected value before you fire off any logic.
Use bind instead, and as the eventdata, send a function that checks that either that both are selected or that the other is selected. Untested code:
function checker() {
// test your conditions
}
$(".TypeFilter").bind('change', {test: checker}, function(event)
{
if (event.data.test && event.data.test()) {
// Extract value from TypeFilter and update page accordingly
}
));
This way the other pages that use the same function will not notice any changes.