Adding a HREF to a JQuery Dynamically Populated Select - javascript

I have a form based menu which automatically populates the select options with the contents of a primary-nav UL. It wonderfully increments the with dashes reflecting the positions of the menu.
However, it doesn't populate the with the HREFs of the links within the ULs.
This is the code that I have:
<script>
$(function() {
var options = '<option selected></option>';
$('#primary-nav').find('a').each(function () {
var text = $(this).text(),
depth = $(this).parent().parents('ul').length,
depthChar = '',
i = 1;
for (i; i < depth; i++) { depthChar += '– ';
}
options += '<option>' + depthChar + text + '</option>';
});
$('<select id=\'mobile-menu\' />').append(options).appendTo('#mobile-nav');
$("#primary-nav select").change(function() {
window.location = $(this).find("option:selected").val();
});
});
</script>
I need to somehow add the below to the above so that when clicked the selected option goes to a url, and not a url based on the displayed value;
$("#primary-nav a").each(function() {
var el = $(this);
$("<option />", {
"value" : el.attr("href"),
"text" : el.text()
}).appendTo("#primary-nav select");
});
Can anyone advise me how I can do this?
Thank you.

You can just add the value attribute in your current code:
$('#primary-nav').find('a').each(function () {
var text = $(this).text(),
href = $(this).attr('href'),
depth = $(this).parent().parents('ul').length,
depthChar = '',
i = 1;
for (i; i < depth; i++) {
depthChar += '– ';
}
options += '<option value="'+href+'">' + depthChar + text + '</option>';
});
$('<select id=\'mobile-menu\' />').append(options).appendTo('#mobile-nav');

Related

How to dyncamically set the value of a dropdownlist from an array

I am trying to get a value from a dropdown list. I have the dropdown list and I have the value that I want but I don't know how to link them to each other. So the value of the category should go in the dropdown list and then the image value from that string should be the outcome.
This is the JSON file array called ill.json
...
[{"id":"7","category":"Lente collectie 2021","image":"Teddy_bears_10.png"},{"id":"11","category":"Lente collectie 2021","image":"Individual_floral_elements_01.png"}
...
The category value goes into the dropdown list and then the outcome should be the image value:
This is my dropdown
...
const req = new XMLHttpRequest();
req.open('GET', 'ill.json', true);
req.send();
req.onload = function() {
const json = JSON.parse(req.responseText);
let dropdown = "";
let html = "";
//FILLING DROPDOWN WITH CATEGORYs
var result = json.reduce(function (r, a) {
r[a.category] = r[a.category] || [];
r[a.category].push(a);
return r;
}, Object.create(null));
let keys = Object.keys(result)
keys.forEach((key) => {
dropdown += "<select id='select'>"
dropdown += "<option value='" + key + "'>"
dropdown += key
dropdown += "</option>"
dropdown += "</select"
})
document.getElementsByClassName('dropdown')[0].innerHTML = dropdown;
...
And this is how I got the images
...
//get all images
json.forEach(function(val) {
html += "<div class='illustratie-item'>";
html += "<img class='dt-filelist-image' src='" + val.image + "'/>"
html += "</div><br>";
});
document.getElementsByClassName('illustratie-wrapper')[0].innerHTML = html;
...
If I get that right, it should be as easy as this:
var categorySelect = document.querySelector('.dropdown');
categorySelect.addEventListener('change', function(evt) {
var item = json.find(function(item) {
return item.id === evt.target.value;
});
console.log(item.image); // there's your image
});
Check the below snippet.
var images = [{"id":"7","category":"Lente collectie 2020","image":"Teddy_bears_10.png"},{"id":"11","category":"Lente collectie 2021","image":"Individual_floral_elements_01.png"}];
var dropdown = '';
dropdown += '<select id="select">';
Object.keys(images).forEach(function(key) {
dropdown += '<option value="' + images[key].id + '">';
dropdown += images[key].category;
dropdown += '</option>';
});
dropdown += '</select>';
document.getElementsByClassName('dropdown')[0].innerHTML = dropdown;
var categorySelect = document.querySelector('#select');
categorySelect.addEventListener('change', function(evt) {
var item = images.find(function(item) {
return item.id === evt.target.value;
});
console.log( item.image );
});
<div class="dropdown"></div>

Using variable for an identifier name (using jquery selectors)

Believe me, I've been looking for examples online for hours. None of them seem to help.
I'm working on making a table. There are some columns with dropdown menu and I've assigned ID to each menu. Inside a loop, I'm trying to assign selected value for each dropdown menu.
var row$ = $('<tr/>');
function updateDataBodyGenerator(myList) {
for (var i = 0 ; i < myList.length ; i++) {
var row$ = $('<tr/>');
var colIndex = 0;
for (var key in myList[i]) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) { cellValue = ""; }
var severityDropDownMenu = "severityDropDownMenu" + i;
colIndex++;
switch (key) {
case "Test Case":
...
break;
case "Test Result":
...
break;
case "Severity":
var severitySting = '<td><select id="' + severityDropDownMenu + '" class="dropDownMenu">' +
'<option value="Red">Red</option>' +
'<option value="Green">Green</option>'+
'<option value="Yellow">Yellow</option>';
row$.append($(severitySting));
//failed
//$("#severityDropDownMenu" + i).val(cellValue);
//failed
//var selectorString = "#" + severityDropDownMenu.toString();
//$(selectorString).val("Green");
//failed
//$("#" + severityDropDownMenu).val(cellValue);
//failed
//var selectorString = '#' + severityDropDownMenu;
//$(selectorString).val(cellValue);
//works
//$('#severityDropDownMenu0').val(cellValue);
...
As you can see in the comments, I've tried several approaches and only 1 worked which was $('#severityDropDownMenu0').val(cellValue); but that will only change 1 dropdown menu.
I appreciate your time and assistance.
Currently you're trying to use the # selector to target the dropdown by ID.
The issue here (as mentioned in the comments) is that this selector will search the DOM for the element, however because you've never added this element to the DOM, it doesn't exist on the page; the selector will return nothing.
What you can do instead is actually turn your severitySting into a jQuery element to set its value. Whenever you do append it, the value will be properly set. Like so:
var $severity = $(severitySting); //This is the <td>
var $dropdown = $severity.find("select") //This is the <select>
$dropdown.val(cellValue); //Set dropdown value
Demo:
var severityDropDownMenu = "mytest";
var cellValue = "Yellow";
var severitySting = '<td><select id="' + severityDropDownMenu + '" class="dropDownMenu">' +
'<option value="Red">Red</option>' +
'<option value="Green">Green</option>' +
'<option value="Yellow">Yellow</option>';
var $severity = $(severitySting);
var $dropdown = $severity.find("select");
$dropdown.val(cellValue);
$("tr").append($severity);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr></tr>
</table>

How do i mark as selected a specific option from a select which his options are loaded depending of an input number?

take your time to read my explanation and ask me if i didn't explain myself well, thanks.
Don't mind how i print whith php, it it okay this way, this is a php setting.
i have in a template an input number that the client will fill with an amount of pallets, in the same template i have a table with as many tr as boxes the order has.
so, there are as many selects as tr, because it is used to assign the box to a pallet.
When the process is done i have the info in my database and if the client enters again he will need to have all the data in place, so the input number is filled and that fills all the selects with the amount of otions as the input, ok.
the fill process is made with jquery.
in the template, i have only this to make the select
<td><select class="pallets_assign" name="boxes[<?=$box;?>][which_pallet]"></select></td>
UPDATE:
to load the options in the selects i use this inside a document ready :
var someone = function() {
var something = function(from_pallets, to_pallets) {
var qty = $(from_pallets);
var select = $(to_pallets);
var update = function() {
select.empty();
for (var i = 1; i <= qty.val(); i++) {
select.append('<option value="' + i + '">' + i + '</option>');
}
};
qty.on('change', update);
update();
}
});
form the tamplate i call it like this:
var init = function() {
someone.something('#total_pallets', '.pallets_assign');
};
total_pallets is the id of the input number
My question is: how do i mark as selected the option which value i have stored in my database if i don't have the options created when the DOM is loaded but when that input number changed?
Thanks for your time.
Thanks to #AlonEitan to helping me find a way to solve this
in the template i had a script that did something like this:
var init = function() {
someone.something('#total_pallets', '.pallets_assign');
};
changed to:
var init = function() {
var option = [];
<? foreach ($products as $product) { ?>
<? for ($i = 1; $i <= count($product["boxes"]); $i++) { ?>
option.push(<?=(somechecks ? $product["boxes"][$i]["which_pallet"] : false);?>);
<? } ?>
<? } ?>
someone.something('#total_pallets', '.pallets_assign', option);
};
and in my js file i had this:
var someone = function() {
var something = function(from_pallets, to_pallets) {
var qty = $(from_pallets);
var select = $(to_pallets);
var update = function() {
select.empty();
for (var i = 1; i <= qty.val(); i++) {
select.append('<option value="' + i + '">' + i + '</option>');
}
};
qty.on('change', update);
update();
}
});
which is now:
var someone = function() {
var something = function(from_pallets, to_pallets, option) {
var qty = $(from_pallets);
var select = $(to_pallets);
var update = function() {
select.empty();
select.each(function(i) {
for (var j = 1; j <= qty.val(); j++) {
$(this).append('<option value="' + j + '"' + (j == option[i] ? ' selected="selected"' : '') + '>' + j + '</option>');
}
});
};
qty.on('change', update);
update();
}
});
It is a shame that in the beginning this got that many downvotes because i think is a cool way to solve this kind of issue and people will profit of this, but anyway.

How to clear a listbox value when another listbox value selected

I have created a depending on radio button click listbox will display now if user click a one radio button listbox will display and again user select other option but its not clear a previous value of listbox how to clear it by javascript????
<script language="JavaScript" type="text/javascript">
function fun(s)
{
if(s==B)
{
document.getElementById("maingroup").style.display='none';
document.getElementById("subgroup").style.display='';
document.getElementById("itemname").style.display='none';
}
if(s==C)
{
document.getElementById("maingroup").style.display='none';
document.getElementById("subgroup").style.display='none';
document.getElementById("itemname").style.display='';
}
</script>
Here is the example which i have tried JS FIDDLE
Try this:
var listBox = document.getElementById("listboxID");
listBox.innerHTML = "";
I think show/hide method is not good for programming.
I dont know whether it is useful or not but this might be helpful to you.
You can make it dynamic like
var mainGroup = ["aa","bb","cc"];
var subGourp = ["dd","ee","ff"];
var itemName = ["gg","ee","ff"];
var Country = ["jj","hh","ii"];
var Zone = ["kk","ll","mm"];
if(s == A)
{
var i=0;
var str = "";
for(i=0;i<mainGroup.length;i++)
{
str += "<option value='" + (i+1) + "'>" + mainGroup[i] + "</option>";
}
document.getElementById("maingroup").style.display='';
document.getElementById("maingroup").innerHTML = str;
}
else if(s == B)
{
var i=0;
var str = "";
for(i=0;i<subGourp.length;i++)
{
str += "<option value='" + (i+1) + "'>" + subGourp[i] + "</option>";
}
document.getElementById("maingroup").style.display='';
document.getElementById("maingroup").innerHTML = str;
}
This is my idea(not tested). Give every your listbox a class name like class='lst'. After that when you click on a radio button just use:
`document.getElementsByClassName('lst').style.display = 'none';`
and show current listbox.
`document.getElementsByClassName('currentListboxID').style.display = 'block';`
Here is DEMO

Remove nested options from select menu - jQuery

I have a simple bit of Javascript.
Is it possible to remove any nested parts of this menu when it becomes a select menu?
So in the demo below, the '- test' part wouldn't appear in the select menu.
DEMO: http://jsfiddle.net/ZBZRw/
My jQuery is:
$(function() {
var options = '<option selected>Go to...</option>';
$('nav div.alt').find('a').each(function () {
var text = $(this).text(),
purl = $(this).attr("href"),
depth = $(this).parent().parents('ul').length,
depthChar = '',
i = 1;
for (i; i < depth; i++) { depthChar += '– '; }
options += '<option value="' + purl + '">' + depthChar + text + '</option>';
});
$('<select />').append(options).appendTo('nav div.alt');
$("nav select").change(function() {
window.location = $(this).find("option:selected").val();
});
});
Many thanks for any advice.
Use the child selector > to be more exact in the <a> elements that you select
$('nav div.alt > ul > li > a').each(function () {
http://jsfiddle.net/ZBZRw/1/

Categories

Resources