Remove nested options from select menu - jQuery - javascript

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/

Related

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>

Check Checkbox in jquery

This is my current code. What I am trying to accomplish is as follows.
If json[i].enabled is true, I need to check the corresponding checkbox. If not, leave it empty.
function createTable(json) {
var element = "";
var i;
for (i = 0; i < json.length; i++) {
element = element
+ '<tr><td><input type= "checkbox"/></td><td>'
+ json[i].a_id + '</td><td>' + json[i].name + '</td><td>'+ json[i].enabled
+ '</td></tr>';
if(json[i].enabled== "TRUE"){
$('checkbox').prop('checked', true);
}
}
//Had forgotten to add this before.
element = element + '</tbody>';
$('#dataTable > tbody').remove();
$("#dataTable").append(element);
}
I tried it by including the following if condition but it fails.
if(json[i].enabled== "TRUE"){
$('checkbox').prop('checked', true);
}
So, how do I go about doing this? How do I access that particular checkbox in the loop?
Thanks!
Using string concatenation and a ternary operator:
'<tr><td><input type="checkbox"' + ( json[i].enabled== "TRUE" ? ' checked' : '' ) + '/></td><td>'
$('input[type="checkbox"]').prop('checked', true);
complete example:
var $table=jQuery('<table></table>');
for (i = 0; i < json.length; i++) {
var $tr=jQuery(
'<tr><td><input type= "checkbox"/></td><td>'
+ json[i].a_id + '</td><td>' + json[i].name + '</td><td>'+ json[i].enabled
+ '</td></tr>');
if(json[i].enabled== "TRUE"){
$tr.find('input["checkbox"]').prop('checked', true);
}
$table.append($tr);
}
$jQuery('body').append($table);
The checbox element has not been created yet in the DOM. So you have to put the html first. Then use
input[type="checkbox"]
to match an actual checkbox element. And at last, you might want to get the last checkbox only (in the last row of your table) with this selector :
mytable tbody tr:last input[type="checkbox"]
So you have the following code :
function createTable(json) {
var i;
for (i = 0; i < json.length; i++) {
// construct the html
element = '<tr><td><input type= "checkbox"/></td><td>'
+ json[i].a_id + '</td><td>' + json[i].name + '</td><td>'+ json[i].enabled
+ '</td></tr>';
// put the html in the page
$('#mytable tbody').append(element);
if(json[i].enabled== "TRUE"){
// get the last inserted line in the table and check the checkbox
$('#mytable tbody tr:last input[type="checkbox"]').prop('checked', true);
}
}
}
Try this:
$('input[type="checkbox"]:eq(i)').prop('checked', true);

How to make list in jQuery mobile nested list?

Can you please tell me how to make list in jQuery mobile? I am trying to make this type list as given in fiddle on pop up screen dynamically .
Here is the fiddle
In this fiddle I make two rows.In first row there is only p tag. But in second row there is nested collapsible rows. I need to make same thing in pop up screen. I am able to make first row. But In my second row contend is null why? Can you suggest where I am wrong?
fiddle
$(function () {
$('#test').click(function(){
alert('d');
createCommandPopUpTabs();
$("#tabbedPopup").popup("open");
});
});
var tabsHeader = [ "InputParameter", "basic"];
var tabsHeader_basic = [ "XYZ", "Third Level",
];
function createCommandPopUpTabs(){
var header = "<h3 >dd</h3>";
var commmand = 'dd';
var button = '<button onclick="return submitCommand("'+
'")" style="" class="donebtn common-button1">Save</button>';
$("#commandInfo").append(button);
$("#commandInfoheader").html(header);
for ( var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>InputParameter</h3></div>";
var content ;
if(tabsHeader[i]=="InputParameter"){
content = "<p>yes</p>";
}else if(tabsHeader[i]=="basic"){
for ( var i = 0; i < tabsHeader_basic.length; i++) {
headerId = tabsHeader_basic[i] + "_tab" + commmand;
header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>basic</h3></div>";
content += getcontend(tabsHeader_basic[i]);
}
}
$("#tabbedSet").append(header);
$("#tabbedSet").find("#" + headerId).append(content);
$("#tabbedSet").collapsibleset("refresh");
}
}
function getcontend(name){
if(name=="Third Level"){
return"<p>Third Level></p>";
} if(name=="XYZ"){
return"<p> second Level></p>";
}
}
There are errors in your code and logic. I will only go over a couple of them to hopefully get you on the right path:
In tabsHeader_basic array the Third Level has a space in it which you later use as an ID which makes it an invalid ID because you cannot have spaces in an ID.
From the HTML 5 Draft:
The value must not contain any space characters.
Also, the "basic" collapsible div needs to exist before you start adding the nested collapsible div.
So this line needs to come out of the for loop
header = "<div data-role='collapsible' data-collapsed='false' id='"+ headerId + "'><h3>basic</h3></div>";
Go through the JSFiddle and compare your code agaisnt my changes.
Hopefully that helps! Let me know if you have any other questions.
I have updated createCommandPopUpTabs() function.
Also removed space in Third Level on var tabsHeader_basic = ["XYZ", "ThirdLevel"];
Check the Updated Fiddle
function createCommandPopUpTabs() {
var header = "<h3 >dd</h3>";
var commmand = 'dd';
var button = '<button onclick="return submitCommand("' +
'")" style="" class="donebtn common-button1">Save</button>';
$("#commandInfo").html(button);
$("#commandInfoheader").html(header);
$("#tabbedSet").html('');
for (var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='true' id='" + headerId + "'><h3>" + tabsHeader[i] + "</h3></div>";
$("#tabbedSet").append(header);
var content;
if (tabsHeader[i] == "InputParameter") {
content = "<p>yes</p>";
$("#tabbedSet").find("#" + headerId).append(content);
} else if (tabsHeader[i] == "basic") {
for (var j = 0; j < tabsHeader_basic.length; j++) {
var headerId1 = tabsHeader_basic[j] + "_tab" + commmand;
var header1 = "<div data-role='collapsible' data-collapsed='true' id='" + headerId1 + "'><h3>" + tabsHeader_basic[j] + "</h3></div>";
var content1 = getcontend(tabsHeader_basic[j]);
$("#tabbedSet").find("#" + headerId).append(header1);
$("#tabbedSet").find("#" + headerId1).append(content1);
}
}
$("#tabbedSet").collapsibleset("refresh");
}
}

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

Adding a HREF to a JQuery Dynamically Populated Select

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

Categories

Resources