Show hidden div when certain value is selected - javascript

I have dynamic fields generated through jquery. I am able to display these fields through a select function trigger .change. Every select field has three options Biology, Calculus and Others-Not listed. When choosing Others-not listed with value of 3, the function displays a hidden div. My problem is that if there are two select fields and one has option Others-not listed chosen it will show the hidden div for all other select. I would like to just show this hidden div for the particular select field. JSFIDDLE
$(document).ready(function() {
$('select').change(function() {
var option = $(this).val();
showFields(option);
return false;
});
function showFields(option){
var content = '';
for (var i = 1; i <= option; i++){
content += '<div id="course_' + i + '"><label>Course # ' + i + '</label><br /><label>Course Name:</label> <select id="coursename_' + i + '" name="coursename_' + i + '" class="ddlcss"><option value="">--- Select ---</option>"'
content += '<option value="1">Biology</option>'; content += '<option value="2">Calculus</option>'; content += '<option value="3">Other - Not Listed</option>'; '"';
content += '</select><div class="hideNewCourse" style="display:none;"><label for="newCourse_'+i+'">Add Course Name to List:</label><input type="text" id="newCourse_'+i+'" name="newCourse_'+i+'"/></div></br></div>';
$(document).on('change',"#coursename_"+i, function(){
if ($(this).val() == "3"){
$(".hideNewCourse").show();
}else{
$(".hideNewCourse").hide();
}
});
}
$('#course_catalog').html(content);
}
});

Change your code for the select fields to:
if ($(this).val() == "3") {
$(this).parent().find(".hideNewCourse").show();
} else {
$(this).parent().find(".hideNewCourse").hide();
}
jsFiddle example
In your code, $(".hideNewCourse") will show or hide all the elements with that class. By using $(this).parent().find(".hideNewCourse") you only select the element relative to the select that was changed.

You are anyways delegating the events. Instead of binding the event to each element specifically just use Attribute starts with selector.
$(document).on('change',"#coursename_"+i, function(){
can be changed to
$(document).on('change',"[id^=coursename_]", function() {
And move it out of the showFields method
And to show and hide the specific element containing to the container, use a mix of closest , which gets to the parent and then find the hideContainer div for that corresponding block.
$(".hideNewCourse").show();
will then change to
$(this).closest('div').find(".hideNewCourse")
Check Fiddle

$(".hideNewCourse").show();
The above represents all the elements with this class.
You have to be selective like
$(this).parent().find(".hideNewCourse").show();
Then,
$(document).on('change',"#coursename_"+i, function(){
if ($(this).val() == "3"){
$(this).parent().find(".hideNewCourse").show();
}else{
$(this).parent().find(".hideNewCourse").hide();
}
});
Fiddle

Try using the .next() function so it only grabs the next object, instead of all of them:
So instead of this:
$(".hideNewCourse").show();
Do this:
$(this).next(".hideNewCourse").show();
And you would do the same for hide:
$(this).next(".hideNewCourse").hide();

Related

TinyNav.js issue, need element ID

So I downloaded TinyNav.js which helps me with my websites menu and can't figure out how to get the element ID from the "a" tag. I have modified TinyNav.js in one spot here.
The code is right here:
https://github.com/viljamis/TinyNav.js/blob/master/tinynav.js
I need help with line 61.
window.location.href = $(this).val();
I changed this line to
window.location.onClick = (A javascript function call which expects a string)
The string in this case is what I need help on. I need to get the SELECTED items ID, and I can't seem to find a way to do that. The
$(this).val();
returns to me the href of the selected item I clicked on in my menu but again, I want just the selected element's ID. How do I get this value?
The <option> elements are created dynamically in the tinyNav script on line 40:
options += '<option value="' + $(this).attr('href') + '">';
They only have a value attribute, no IDs.
I'm assuming that your ID values are inside you <a> tags, such as:
About
You can grab the IDs and put them into your options like this:
options += '<option value="' + $(this).attr('href') + '" id="' + $(this).attr('id') + '">';
Then you can get the ID inside the change function.
Change this (lines 60-62):
$select.change(function () {
window.location.href = $(this).val();
});
To this:
$select.change(function () {
console.log($(this).find(":selected").attr('id'));
window.location.href = $(this).val();
});
The value of $(this) is the select element that is being changed. Then you can use .find(":selected") to get the selected option element, and finally .attr('id') to get the ID attribute.
Here is a jsfiddle: https://jsfiddle.net/t72wdcwc/41/
window.location.onClick is incorrect. Javscript is case-sensitive and uses onclick, with no camelCase. You can do the following:
window.location.onclick = function() {
yourFunction($(this).attr("id"));
}
function yourFunction(id) {
alert("You clicked " + id);
}

jQuery General function to get value of :input selector

Is there a way to get the value of an :input in jQuery that holds for all :input?
I am asking this because I have a page with select and checkbox, it is for the following code:
for (var i = 0; i < arguments.length; i++) {
var localArgument = arguments[i].trim();
data[localArgument] = $(html).find(":input[name='" + localArgument + "']").val();
$(html).on("change", ":input[name='" + localArgument + "']", function(event) {
console.log(localArgument + ": " + $(this).val());
data[localArgument] = $(this).val();
reloadTable(table, html, data);
});
}
Where arguments is an array that holds names for elements.
I know I need to do it for checkbox with .prop("checked"), however I would much rather use a general function which I know does not need to be updated in the future.
just use $('input') selector to select all input elements
If you want to get the value of each input element you can do something like
$('input').each(function() {
// use $(this).val() to get the value
})
You can safely use val() for all inputs, checkboxes, radio buttons, and selects. This is a demo: http://jsfiddle.net/FxjQB/3

Update text input field dynamically using two select menus with Javascript

I am trying to figure out how to dynamically update a text input field when a user changes the option in one or two HTML select menus. I have included my code below showing how it currently works.
$('tickets').addEvent('change', function() {
if($('tickets').value > 0)
{
var cells = $$('.ticket2');
cells.each(function(cell) { cell.setAttribute('style','display:none;');});
var cells = $$('.ticket3');
cells.each(function(cell) { cell.setAttribute('style','display:none;');});
var sumValue = '$' + (100 * $('tickets').value + 10 * $('fiftytickets').value) + '.00';
$('ordertotal').value = sumValue;
$('ticket1heading').setHTML('Ticket(s)');
} else {
var cells = $$('.ticket2');
cells.each(function(cell) { cell.setAttribute('style','');});
var cells = $$('.ticket3');
cells.each(function(cell) { cell.setAttribute('style','');});
$('ticket2heading').setAttribute('style','text-align:center; font-weight:bold;');
$('ticket3heading').setAttribute('style','text-align:center; font-weight:bold;');
$('ordertotal').value = '$' + 250 + '.00';
$('ticket1heading').setHTML('Ticket 1');
}
});
The tickets select menu correctly affects the ordertotal text input field, but the fiftytickets select menu does not. I need the two to work independently of each other, but when each is changed, to affect the value of the ordertotal text input field.
Any assistance is greatly appreciated.
Thank you.
Mike
as said by JoDev, the select element's object is referenced with $('#tickets') and not just $('tickets').
also, I don't think that there is a value property in jquery for a select element.
you can get the value with the val() function.
Created a little fiddle for you here here
$('#tickets').change(function() {
$('#output').val($(this).val() + " - " + $('#fiftytickets').val());
});
$('#fiftytickets').change(function() {
$('#output').val($('#tickets').val() + " - " + $(this).val());
});

JavaScript For loop appending 4 times

I have a JavaScript program that isn't properly functioning. For some reasons before it appends what it is actually getting from the checked radio box it appends three times with noting in the append except the styling. I'm not sure what I'm doing wrong.
$(document).delegate('#add-owner', 'pageinit', function () {
loadOwners();
$('#add-owner-save').bind('click', function () {
var permission = $('#editing-permissions option:selected').text();
var selection = $("input[type='radio']:checked") || [];
if (selection.length > 0) {
for (var i = 0; i < selection.length; i++) {
console.log($('#label-' + selection[i].id).find('.owner-name').text());
console.log($("input[type='radio']:checked").val());
$('.display-owners').append('<div class="ui-grid-a"><div class="ui-block-a">' + $('#label-' + selection[i].id).find('.owner-name').text() + '</div><div class="ui-block-b" style="text-align:right">' + permission + '</div></div>');
}
$('.display-owners').trigger('create');
}
$('.display-owners').show();
$('#add-owner').dialog('close');
$('input[name=contribute-radio]').attr('checked', false).checkboxradio("refresh");
return false;
});
});
I think the problem is that I have multiple radio areas on this page. How do I specify that I just want these radio buttons are the ones I want it to checked?
This code:
... + $('#label-' + selection[i].id).find('...
should be like this:
... + $('#label-' + selection[i].attr('id')).find('...
because what you have in selection array are jQuery objects, not DOM elements objects.
Thanks Esalija for pointing out my assumption was not correct.
Since said you have multiple sets of radio buttons, the selector you're using is finding all of them on the page so that is why you have multiple "checked" radio buttons.
This:
var selection = $("input[type='radio']:checked") || [];
To this:
var selection = $("input[name='radioset1']:checked") || [];
Then just name each radio set different and replace "radioset1" with the set you need for this one.

Need help with a JavaScript function to de-select items in jQuery DropdownChecklist

I'm working on an ASP.Net webpage which will use the jQuery Dropdown Checklist (http://code.google.com/p/dropdown-check-list/). I'm fairly inexperienced with JavaScript and completely new to jQuery.
Could anyone help me with a JavaScript function that de-selects items from a jQuery DropdownChecklist? It would need to accept a string, then de-select the item that matches that string.
Thanks in advance.
Try changing the original <select> element so that the item you want to deselect is no longer selected and then refresh the jQuery dropdown-checklist using the "refresh" command. Something like this (where selectID is the ID of the original <select> element and targetString is the content of the <option> you want to deselect):
function deselect(selectID, targetString){
$("#" + selectID + " option").each(function(){
if($(this).text() === targetString) $(this).attr("selected", "");
});
$("#" + selectID).dropdownchecklist("refresh");
}
Following code deselects item and removes it from display.
document.clearSel = function(list,txt){
var ele=document.getElementById(list);
for(i=0; i < ele.options.length; i++ ) {
if (ele.options[i].selected && (ele.options[i].text == txt) &&
(ele.options[i].value != "")) {
var val=ele.options[i].value;
$("div#ddcl-" + list +"-ddw input[value='"+val+"']").each(function(){
$(this).attr("checked",false);
var spSel="span#ddcl-" + list +" span.ui-dropdownchecklist-text";
var spTxt=$(spSel).text();
$(spSel).text(spTxt.replace(txt+",",'').replace(txt,''));
});
}
}
}
document.clearSel("s8","Low");
I got "div#ddcl--ddw input[value='']" and "span#ddcl- span.ui-dropdownchecklist-text" selectors after examining demo page for drop down check list
PS:- I've trie $("#" + list).dropdownchecklist("refresh"); but I am not able to refresh the text;

Categories