Accessing the content value from within 3 classes in Javascript - javascript

So I have a dropdown box with values "No" and "Yes" but it will not property display it when selected. It just comes up as blank. No matter what I choose, I want it to display what I have chosen, either "Yes" or "No".
So I got the class names for everything that I need.
For the selected value that is being displayed in the dropdown box is:
<a class="select2-choice" tabindex="-1" onclick="return false;" href="javascript:void(0)">
<span class="select2-chosen">No</span>
<abbr class="select2-search-choice-close"></abbr>
.....
</a>
The dropdown box html code is:
<ul class="select2-results">
<li class="select2-results-dept-0 select2-result select2-result-selectable">
<div class="select2-result-label">No</div>
</li>
<li class="select2-results-dept-0 select2-result select2-result-selectable select2-highlighted">
<div class="select2-result-label">Yes</div>
</li>
</ul>
So I want to access the values of select2-result-label and set them to the select2-chosen content value. I tried doing it, but it's giving me an error in FireBug.
Here's what I did so far... What am I doing wrong?
function testFunc() {
var x = document.getElementsByClassName("select2-chosen");
var y = document.getElementsByClassName("select2-results-dept-0 select2-result select2-result-selectable select2-highlighted")
.getElementsByClassName("select2-result-label");
x[0].innerHTML = y;
}

You are using getElementsByClassName in the wrong context. This function merely returns all elements that have any of the specified class names.
As select2-highlighted is only assigned to a selected element, it's the only class you should care about. Making these changes should help:
function testFunc() {
var x = document.getElementsByClassName("select2-chosen");
var y = document.getElementsByClassName("select2-highlighted")[0].getElementsByClassName("select2-result-label");
x[0].innerHTML = y[0].innerHTML;
}

It should work with
x[0].innerHTML = y[0].innerHTML;
But why did you make it so f=difficult for yourself? Why didn't you use radio buttons, for instance? And why didn't you use id's?

EDIT
replace
"var y = document.get..."
with
"var y = document.getElementsByClassName("select2-results-dept-0 select2-result select2-result-selectable select2-highlighted")[0].children[0].innerHTML;"
=========================================================================
Try something like this to make use of radio buttons, as Sylvia suggested:
window.setAnswer = function(dom) {
var els = document.getElementsByTagName('input');
for (el in els)
{
if (els[el].checked)
{
document.getElementsByTagName('h1')[0].innerHTML = els[el].nextSibling.nodeValue;
break;
}
}
}
<input type="radio" name="radio" onclick="setAnswer()">Yes</input><br>
<input type="radio" name="radio" onclick="setAnswer()">No</input><br>
<h1></h1>

Related

need help to add and remove items from list with jQuery

I'm trying to add and remove sub items with price calcuation with following piece of jQuery
$('.sub_item-plus-button').click( function() {
var li_id = $(this).closest('li').attr('id');
var productname = $('#'+li_id+' > .name').text();
var productPrice = $('#'+li_id+' .price').text();//alert(productPrice);
var parent_cat = $('#temp > #main_category').text();
var price = $('#'+li_id+' .price').text();//alert(price);
$("#product-form").append('<input type="text" id="'+li_id+'" name="prdname[]" value="'+productname+'" />');
$("#product-form").append('<input type="text" id="'+li_id+'" name="prdprice[]" value="'+productPrice+'" />');
$("#product-form").append('<input type="text" id="'+li_id+'" name="prdparent[]" value="'+parent_cat+'" />');
//$("#product-form").append('<input type="text" name="sub_category" value="'+price+'" />');
$('li#'+li_id).append('<li id="'+li_id+'" class="extras"><span class="name">1</span><span class="price">1.00</span><span class="right"><span class="icon-minus-sign-empty">Re</span></span></li>');
set_total_price(productPrice);
});
And HTML is
<ul id="sub_item">
<div class="addExtrasTotal"><span>Total</span> £<span class="totalPrice">0.00</span></div>
<li id="ext1" class="popextra" style="clear: both;"><span class="column6 name">Anchovies</span>
<span class="column6 right">£ <span class="price">1.00</span>
<a class="button item-plus" href="JavaScript: void(0);"><span class="sub_item-plus-button">+</span></a>
</span>
</li>
<li id="ext2" class="popextra" style="clear: both;"><span class="column6 name">Artichokes</span>
<span class="column6 right">£ <span class="price">1.00</span>
<a class="button item-plus" href="JavaScript: void(0);"><span class="sub_item-plus-button">+</span></a>
</span>
</li>
</ul>
The Problem with I need help is;
1.When Adding, first time, it adds 1 item, 2nd time, it add 2 items instead of 1 and 3rd time click it adds 3 items.
2.When removing items, it removes all the items on single click in one go but remove price of single item from total and rest of the sub items price still added in total.
Price & item remove function is;
function ri(li_id){
//alert(li_id);
var price = $('#'+li_id+' .price').text(); //alert(price);
var extrass = $('#'+li_id+' .extras').html(); alert(extrass);
$('#'+li_id+' .extras').remove();
set_total_price_minus(price);
}
Really appericate the help to figure out the problem and solution.
Regards
The issue is due to id ambiguity. You are assigning the same id attribute to multiple elements in the $('.sub_item-plus-button').click() function, so jQuery gets confused when trying to select these elements by id. The id attribute is meant to be unique, so only a single element should be assigned a given id.

JQuery Multiple Hidden Values

I have the following HTML;
<ul class="list-group">
<li class="list-group-item">
www.andrewspiers.co.uk
<input type="hidden" name="url" value="www.andrewspiers.co.uk">
</li>
<li class="list-group-item">
wikipedia.org
<input type="hidden" name="url" value="wikipedia.org">
</li>
</ul>
The plan is to add a button to each row and then get the value from the hidden field when the button is clicked.
I have this;
alert( $('input[name="url"]').val() );
But that returns the value of the first row no matter which button is clicked.
This should work:
$('button').click(function(){
console.log($(this).closest('li').find('input[name="url"]').val())
})
You need to use $(this) within the click function to refer to that specific element and then traverse the DOM accordingly (multiple ways to skin a cat on this one) to get the hidden input.
jsFiddle example
Assuming your buttons are placed inside the same li, you need a more specific selector:
alert( $(this).siblings('input[name="url"]').val() );
You can add buttons like this :
$('.list-group-item').each(function(){
$(this).append('<input class="clicked" type="button" value="Click me"/>')
})
YOu can then get value of each hidden according to the button like this:
$('.clicked').on('click',function(){
var hiddenval =$(this).parent().find('input[name="url"]').val();
console.log(hiddenval);
})

Assigning checkbox values to variables

I've got a list of possible checkboxes and the user can select up to three options. What I'm struggling with is how to recognize which boxes are checked, and then assign them to variables (to send in a later ajax call). So far the code I've written seems to just take the first three checkbox values regardless of whether they are checked or not and use those in my ajax call. Please help me figure out where I've gone wrong.
Here's my HTML:
<ul id="Names" class="stateNames">
<li>Alabama
<ul class="airports">
<li><input type="checkbox" class="destination"/> Birmingham, AL</li>
<li><input type="checkbox" class="destination"/> Huntsville, AL</li>
</ul>
<li>Alaska
<ul class="airports">
<li><input type="checkbox" class="destination"/> Anchorage, AK</li>
<li><input type="checkbox" class="destination"/> Fairbanks, AK</li>
<li><input type="checkbox" class="destination"/> Juneau, AK</li>
</ul>
</li>
</ul>
<input type="button" onclick="clickHandler()" value="Submit" />
Here's my javascript/jquery:
function clickHandler() {
endLocDest1 = "";
endLocDest2 = "";
endLocDest3 = "";
for(i = 0; i < document.getElementsByClassName('destination').length; i++) {
if (document.getElementsByClassName('destination')[i].checked) {
endLocDest1 = document.getElementsByClassName('destination')[0].value;
endLocDest2 = document.getElementsByClassName('destination')[1].value;
endLocDest3 = document.getElementsByClassName('destination')[2].value;
}
alert(endLocDest1 + endLocDest2 + endLocDest3);
};
}
I've also put this code into a fiddle http://jsfiddle.net/6ywm1n6h/3/ (which currently doesn't return anything).
Thanks in advance!
In your jsfiddle, you had jQuery turned on, assuming that, try using ...
$(".destination:checked")
Which will return all checked; you can use this as an array and determine which are clicked.
EDIT:
You can assign this to a variable, say ...
var checked_values = $(".destination:checked");
... then loop through and do what you need.
for (var i=0,len=checked_values.length; i<len; i++) {
console.log(checked_values[i].attr("id"));
}
If your code is wrapped in <form> and </form> then checked inputs will be sent automatically when form is submitted (normaly or AJAX'ed). Your mistake is that you do not set names nor values to your checkboxes. Try:
<input type="checkbox" name="airport[alabama][]" value="Birmingham">
<input type="checkbox" name="airport[alabama][]" value="Huntsville">
<input type="checkbox" name="airport[alaska][]" value="Anchorage">
<input type="checkbox" name="airport[alaska][]" value="Fairbanks">
and see print_r($_POST) or print_r($_GET) (depending on your form method) in page which receives form submission.

Getting the selected radio button from radio buttons inside a div?

I have a div which contains several radio buttons, like this:
<div name="type" id="type">
<ul class="options-list">
<li>
<input type="radio" name="myname1" value="121312" id="myid1">somevalue
</li>
<li>
<input type="radio" name="myname2" value="121312" id="myid2">somevalue
</li>
</ul>
</div>
Now one of the two is checked, how could I get that one using plain JavaScript or PrototypeJS?
Thanks!
You can use,
if(document.getElementById('myid1').checked){
alert(document.getElementById('myid1').value)
}
if(document.getElementById('myid2').checked){
alert(document.getElementById('myid2').value)
}
Just giving an idea.
Well assuming they all have the same name you could do this:
function getCheckedRadio(rbGroupName) {
var rb = document.getElementsByName(rbGroupName);
for (i = 0; i < rb.length; i++) {
if (rb[i].checked) {
return rb[i].id;
}
}
}
Now you could call this within a click/change event handler to return the ID.

jQuery product filter using checkboxes and :contains() show/hide

I'm attempting to put together a simple jQuery product filter for a store that lists all products of a category on one page. This can't be achieved through AJAX because of the way the store is set up.
Simply put, all products of the category are on one page. They have varying brands product names and team names. The markup looks something like this (the form at the end is how I'm planning on doing the filter).
<div id="CategoryContent">
<ul>
<li class="product">Brand1 PRODUCT1 TeamA</li>
<li class="product">Brand1 PRODUCT2 TeamB</li>
<li class="product">Brand2 PRODUCT3 TeamB</li>
<li class="product">Brand2 PRODUCT4 TeamC</li>
<li class="product">Brand3 PRODUCT5 TeamA</li>
<li class="product">Brand3 PRODUCT6 TeamD</li>
<li class="product">Brand4 PRODUCT7 TeamD</li>
<li class="product">Brand1 PRODUCT8 TeamA</li>
<li class="product">Brand1 PRODUCT9 TeamA</li>
<li class="product">Brand1 PRODUCT10 TeamB</li>
<li class="product">Brand4 PRODUCT11 TeamD</li>
<li class="product">Brand2 PRODUCT12 TeamA</li>
</ul>
<div style="clear:both;"></div>
<div class="filter">
<form id= "brandfilter" action="">
<h2>Brands:</h2>
<input type="checkbox" name="brand" value="Brand1"/>Brand1 </br>
<input type="checkbox" name="brand" value="Brand2"/>Brand2 </br>
<input type="checkbox" name="brand" value="Brand3"/>Brand3 </br>
<input type="checkbox" name="brand" value="Brand1"/>Brand4 </br>
</form>
<form id="teamfilter" action="">
<input type="checkbox" name="team" value="TeamA"/>TeamA </br>
<input type="checkbox" name="team" value="TeamB"/>TeamB </br>
<input type="checkbox" name="team" value="TeamC"/>TeamC </br>
<input type="checkbox" name="team" value="TeamD"/>TeamD </br>
</form>
I have found this filter works as I want. In console replacing hide with show and Brand1 with Brand2, TeamA, etc works just fine.
$("#CategoryContent li").not(
$("#CategoryContent li:contains(Brand1)")
).hide();
The next step is getting a double filter which works as well:
$("#CategoryContent li").not(
$("#CategoryContent li:contains(Brand1):contains(TeamA)")
).hide();
My problem with getting this working is two fold. 1 is replacing the Brand1 / Team A with variables (hence the formids).
The second is trying to run the script when a checkbox is clicked. It should work if either one is clicked and if both are clicked (meaning that with the script above it would need to reset by showing all and then hiding).
Currently to initiate it I'm running this script but I'm running into problems so I've gone back to just 1 filter.
$("input:checkbox[name='brand']").click(function() {
var brandfilter = $(this).val();
alert (brandfilter);
$("#CategoryContent li:contains(' + brandfilter + ')").parent().hide();
});
The alert that pops up is what I want (i.e. Brand1) but the hide function afterwards doesn't work and when I alert (brandfilter) again in console again I get [object HTMLFormElement]. So I think the variable isn't storing correctly or something?
Here is the simple working basic script http://jsfiddle.net/7gYJc/
Assuming you want to show items which match any currently ticked box, you can use this:
$('input:checkbox').change(showHideProducts);
function showHideProducts()
{
var checked = $('input:checked');
var products = $('.product');
// If all the boxes are unchecked, show all the products.
if (checked.length == 0)
{
products.show();
}
else
{
products.hide();
checked.each
(
function()
{
$('.product:contains("' + $(this).val() + '")').show();
}
);
}
}​
EDIT: Since you want all the boxes to display when nothing is checked, just add an if (length = 0) check and show everything in there (see above).
I can't tell where the problem is but you can try using filter() instead of the :contains selector. With filter() you can create your own custom filtering rules as it takes a function as parameter.
var myProducts = function (brand, team) {
brand = brand || '';
team = team || '';
return $('.product').filter(function () {
var re = new RegExp(brand + '.+' + team, 'i');
return re.test($(this).text());
});
};
myProducts('Brand1', 'TeamA').hide();
myProducts('Brand2').hide();
Example: http://jsfiddle.net/elclanrs/hYZcW/
I came up with the following approach:
Start with all the checkboxes checked, because you want to show all the products. If the user unticks a checkbox, then it should hide products matching that brand/team.
Here is the code I had:
var $filters = $("input:checkbox[name='brand'],input:checkbox[name=team]").prop('checked', true); // start all checked
var $categoryContent = $('#CategoryContent li'); // cache this selector
$filters.click(function() {
// if any of the checkboxes for brand or team are checked, you want to show LIs containing their value, and you want to hide all the rest.
$categoryContent.hide();
$filters.filter(':checked').each(function(i, el) {
$categoryContent.filter(':contains(' + el.value + ')').show();
});
});​
jsFiddle link.
I had the same kind of problem this week with multiple selects. The selectors worked fine, but hide did not work. I was able to solve it using
.css('visibility', 'hidden'); // instead of .hide() and
.css('visibility', ''); // instead of .show()
I do not understand it, but it worked.

Categories