Show or hide div based on selection - javascript

I am new to JQuery and I want to make a simple function. I have a div that is named based on an id of a checkbox. I want the div to be shown only if its checkbox is checked but the code is not working. It show me this error ($courseTimeDiv.hide is not a function).
this is the part where I define the checkbox
`$programList .= ' <div class="form-check proDiv">
<input type="checkbox" name="course[]" class="form-check-input group2"
id="'.$coursePrice.'" value="'.$courseId.'">
<label class="form-check-label" for="'.$coursePrice.'">'.$courseName .'
price is '.$coursePrice.'$</label>
</div>';`
this is the part of HTML code where I define the div
` $programList .= '<div name="timeDiv'.$courseId.'" class="timeGroup" >
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" id="timeRadio"
value="Weekday" name="time['.$courseId.']" />
<label class="form-check-label"><strong>Weekdays</strong>
</div> </div>';
`
and this is the JQuery code
`$("input[name='course[]']").on('change', function () {
var $courseIdValue = $('input[name="course[]"]:checked').val();
var $courseTimeDiv = $("input[name='timeDiv']") + $courseIdValue;
if($courseTimeDiv.match(/$courseIdValue/)) {
$courseTimeDiv.show(300);
}
else {
$courseTimeDiv.hide();
}
});`
any help is appreciated

var $courseTimeDiv = $("input[name='timeDiv']") + $courseIdValue;
what are you trying to do in this line?
IF, you're trying to select an element, then you can't use match method on it in the next line
IF, you're trying to create element's selector, then js engine is right and your variable does not have an element so you can select it
and in both scenarios you're doing it wrong because you're selecting an input element with name='timeDiv'+blabla while in your code there is no such element
I believe you meant
var selector = "div.timeDiv" + $courseIdValue
var $courseTimeDiv = $(selector);
it's not this simple
you have multiple checkboxes and each checkbox has it's own value, and you want all the selected ones
so
you need to process them to see which one is selected and which one is not, and match method won't help you in this process
`$("input[name*='course']").on('change', function () {
var value = $(this).val();
var selector = "div[name*=[timeDiv" + value + "]"
var courseTimeDiv = $(selector);
if( $(this).is(':checked') ){
courseTimeDiv.show(300);
} else {
courseTimeDiv.hide();
}
});`
I think this should work!
=========UPDATE==========
Previous code works, but it can be wrote in this way to have better performance
`$("input[name*='course']").on('change', function () {
var value = this.value;
var selector = "div[name*=[timeDiv" + value + "]"
var courseTimeDiv = $(selector);
if( this.checked ){
courseTimeDiv.show(300);
} else {
courseTimeDiv.hide();
}
});`

Related

Checkbox check event is not getting prevented

I have a set of set of checkboxes on which I want to restrict to check maximum of one. If the choice needs to be changed then first checked ones need to be unchecked but maximum limit needs to be one.
Here is the jquery code.
$('#ReportRow').on('click', 'input[type="checkbox"]', (function (event) {
alert("Hi");
var checkedReportValues = $('#ReportRow input:checkbox:checked').map(function () {
return this.value;
}).get();
if ($("#ReportRow input:checkbox:checked").length > 1) {
return false;
}
alert(checkedReportValues);
})
);
Here, the above code is restricting only one checkbox to be checked but when I am trying to check other, they first are being checked and then unchecked. Where I am doing wrong ?
Here is the dynamically created HTML.
//Add Code to Create CheckBox dynamically by accessing data from Ajax for the application selected above
var Reports = " User, Admin, Detail, Summary";
var arrReportscheckBoxItems = Reports.split(',');
var reportscheckBoxhtml = ''
for (var i = 0; i < arrReportscheckBoxItems.length; i++) {
reportscheckBoxhtml += ' <label style="font-weight: 600; color: #00467f !important;"><input type="checkbox" value=' + arrReportscheckBoxItems[i] + '>' + arrReportscheckBoxItems[i] + '</label>';
}
//Add Submit button here
reportscheckBoxhtml += ' <button type="button" id="SubmitReport" class="btn btn-primary">Submit</button>';
$('#ReportRow').html(reportscheckBoxhtml);
Try this: uncheck all other checkboxes except clicked one inside click event handler, like below
$('#ReportRow').on('click', 'input[type="checkbox"]',function(){
$('#ReportRow input[type="checkbox"]').not(this).prop("checked",false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ReportRow">
<input type="checkbox">one
<input type="checkbox">Two
<input type="checkbox">Three
<input type="checkbox">Four
</div>
This line:
if ($("#ReportRow input:checkbox:checked").length > 1) {
return false;
}
is saying you want to uncheck the checkbox. It's doing exactly what you tell it to do. Just a comment: Users may be confused since checkboxes are meant to check multiple selections. Radio buttons are designed for being able to select only one option.
you are returning false from the function when there is a checkbox already selected, which is preventing the checkbox selection.
if ($("#ReportRow input:checkbox:checked").length > 1) {
return false;
}
Do something like this:
$('#ReportRow').on('click', 'input[type="checkbox"]', (function (event) {
alert("Hi");
var curCheckBox = this;
$('#ReportRow').find('input[type="checkbox"]').each(function() {
if(this === curCheckBox)
$(this).attr("checked",true);
else
$(this).attr("checked",false);
});
alert(checkedReportValues);
});

Jquery + When all previos fields (radio buttons,select and textbox) are filled then append a new box

This is my html output.
When user click on + (Add Tab) icon then how to check previos fields are filled or not
If any fields is empty then a error message will come.
jQuery('.add-contact').click(function (e) {
e.preventDefault();
// check previous box is field or not
{check code}
var siteUrl = jQuery(this).data('url');
var productId = jQuery(this).data('id');
var id = jQuery(".nav-tabs").children().length; //think about it ;)
var tabId = 'personalize_' + id;
jQuery(this).closest('li').before('<li>Personalize <span> x </span></li>');
var DataPersionalize = '<div class="tab-pane" id="' + tabId + '">';
DataPersionalize += '</div>';
// append data
jQuery('.tab-content').append(DataPersionalize);
jQuery('.nav-tabs li:nth-child(' + id + ') a').click();
});
How it is possible in case of radio button.
Thank
You could create an if else statement with all of the items in the original conditional separated by && and check if each of your input fields has a value with a length > 0 and for the radio button do $('.radio_button').is(':checked')) If they all pass then you can open the tab. If they don't pass you can $('.error-div').html("<div>Error Message</div>")
In case your radiobuttons all are in a group called ring and only one is selectable:
var isChecked = false,
radios = document.getElementsByName("ring");
for(radio in radios) {
isChecked = radios[radio].checked || isChecked;
}
console.log(isChecked);
HTML:
<input type="radio" id="ring1" name="ring">
<input type="radio" id="ring2" name="ring">
In case more than one are selectable, the same solution is usable, as long as you get the collection of required in the variable radios, lets say, id you use a class rings:
var radios = document.getElementsByClassName("rings");
HTML:
<input type="radio" id="ring1" class="rings">
<input type="radio" id="ring2" class="rings">

Same function for different sections - relative referencing in jquery

By using relative references I am able to remove items which have been added to the list within a specfic part of the form. For example, by adding a requirement it can be deleted just from the requirement.
My issue is two fold:
Adding an item to references adds it to all three categories
When I try to add values to the other sections (qualifications) it says my input was blank.
http://jsfiddle.net/spadez/9sX6X/60/
var container = $('.copies'),
value_src = $('#current'),
maxFields = 10,
currentFields = 1;
$('.form').on('click', '.add', function () {
value_src.focus();
if ($.trim(value_src.val()) != '') {
if (currentFields < maxFields) {
var value = value_src.val();
var html = '<div class="line">' +
'<input id="accepted" type="text" value="' + value + '" />' +
'<input type="button" value="X" class="remove" />' +
'</div>';
$(html).appendTo(container);
value_src.val('');
currentFields++;
} else {
alert("You tried to add a field when there are already " + maxFields);
}
} else {
alert("You didn't enter anything");
}
})
.on('click', '.remove', function () {
value_src.focus();
$(this).parents('.line').remove();
currentFields--;
});
Is it possible to modify this code without repeating it for each section, by using relatively references such as "parent" for example. I want to use this same script for all three sections but have it so each list is independant.
I'm new to javascript so I was wondering if this is possible because I only managed to get it working on the delete.
You have to use this to get the current element. In your case this refers to the button which was clicked.
The next step is to get the input box which belongs to the button. E.g. $(this).prev(); like in this example:
$('.form').on('click', '.add', function () {
var value_src = $(this).prev();
http://jsfiddle.net/9sX6X/62/
The same is also true for your appending part. Your are appending your html to all three elements which match $('.copies'). Instead you have to try to get there from this.
$('.form').on('click', '.add', function () {
var value_src = $(this).prev();
var copies = $(this).parent().prev();
http://jsfiddle.net/9sX6X/63/
I would suggest adding a wrapping div to each section.
<div class="section">
<h4>Requirements</h4>
<div class="copies"></div>
<div class="line">
<input id="current" type="text" name="content" placeholder="Requirement" />
<input type="button" value="Add" class="add" />
</div>
</div>
Then you can do this:
var $section = $(this).closest(".section");
$(html).appendTo($section.find(".copies"));
This will add to just the related .copies element instead of to all .copies as your code does now. A similar approach can be used for all other elements as well.

Update price after checkbox is selected

I have a fairly simple problem (I think) that involves updating a number using jQuery. I have a DIV that holds a price for an item. Users can select a checkbox to add on to the total price. What I need is when someone clicks on a checkbox, it will add the correct amount to the DIV. When a user un-checks a checkbox, the value is subtracted. Here is my code so far:
<div class="cell">
<div class="check">
<input id="check-0" type="checkbox" />
<label for="check-0">$100</label>
<div class="mask"></div>
</div>
</div>
<div class="price">$347</div>
Any help is greatly appreciated!
Hopefully this is something that you could use or help you:
http://jsfiddle.net/VWRAd/
$(".cell").on("click", "input:checkbox", function () {
var $this = $(this);
var $total = $("#price");
var $target = $("label[for='" + $this.attr("id") + "']");
var item_value = +($target.html().replace("$", "") || 0);
var cur_total = +($total.html().replace("$", "") || 0);
if ($this.prop("checked") === true) {
cur_total += item_value;
} else {
cur_total -= item_value;
}
$total.html("$" + cur_total);
});
Although notice that I changed the element with the class of "price" to have an id of "price". It just makes sense, unless you expect to have several "price" elements.
And here is another possible way of doing it...not sure which is better:
http://jsfiddle.net/VWRAd/1/
$(".cell").on("click", "input:checkbox", function () {
var $items = $(".cell").find("input:checkbox:checked");
var $total = $("#price");
var cur_total = 0;
$items.each(function () {
var $this = $(this);
var $target = $("label[for='" + $this.attr("id") + "']");
var item_value = +($target.html().replace("$", "") || 0);
cur_total += item_value;
});
$total.html("$" + cur_total);
});
Some things to consider - it makes sense to separate the "$" from the actual value of the item when displaying it...I'm sure you aren't storing the value with "$", so you might want a structure similar to <label for="whatever">$<span class="the-value">100</span></label>. It would change your jQuery selector logic a little bit, but it would prevent the need for using .replace so often. Also, as someone else already pointed out, it would definitely be easier to store the item's price in the checkbox's value attribute and retrieve it that way (instead of finding the corresponding <label>'s content.
var changePrice = function changePrice(amt, state){
var curPrice = $('.price').text();
curPrice = curPrice.substring(1, curPrice.length);
if(state==true){
curPrice = parseInt(curPrice) + parseInt(amt);
}else{
curPrice = parseInt(curPrice) - parseInt(amt);
}
curPrice = '$' + curPrice;
$('.price').text(curPrice);
}
$(function(){
$('#check-0').on('change', function(){
var itemPrice = $('label[for="check-0"]').text();
itemPrice = itemPrice.substring(1, itemPrice.length);
changePrice(itemPrice, $('#check-0').is(':checked'));
});
})​;​
Demo: http://jsfiddle.net/pratik136/r2Snu/
Even though these may not be form controls intended to hit the server, i would still put the value attribute for each of the inputs.
So for the 'check-0' input, i'd put in a value attribute of 100 (to represent the $100).
Then, a bit of javascript logic should make it easy to update the price value.
So something like this should do it (http://jsbin.com/orodow/1/edit):
<div class="cell">
<div class="check">
<input id="check-0" type="checkbox" value="100" />
<label for="check-0">$100</label>
<div class="mask"></div>
</div>
</div>
<div class="cell">
<div class="check">
<input id="check-1" type="checkbox" value="50" />
<label for="check-1">$50</label>
<div class="mask"></div>
</div>
</div>
<div class="cell">
<div class="check">
<input id="check-2" type="checkbox" value="20" />
<label for="check-2">$20</label>
<div class="mask"></div>
</div>
</div>
<div class="price"></div>
<script>
$(function(){
var inputs = $('.check input:checkbox');
function updatePrice(){
var value = 0;
inputs.filter(':checked').each(function(){
value += parseInt($(this).val(), 10);
});
$('.price').html('$' + value);
}
inputs.change(updatePrice);
});
</script>

Add a checkbox for the innerHTML in javascript

I have a page which contains a 10 items(formatted list).Here in this page I need to add check box for each item and add the item as the value to each check box.when the user click on the check box the selected value should be passed to a new page.Can anyone help me how to add a check box for the innerHTML in java script.
Code:
var newsletter=document.getElementById("block-system-main");
var districolumn=getElementsByClassName('view-id-_create_a_news_letter_',newsletter,'div');
if(districolumn!=null)
{
var newsletterall=newsletter.getElementsByTagName('li');
alert(newsletterall[0].innerHTML);
var all=newsletter.innerHTML;
newsletter.innerHTML="<input type='button' onclick='changeText()' value='Change Text'/>";
}
function changeText()
{
alert("dfgsdg");
}
I don't exactly understand what each part of your code is doing, but i'll try and give a general answer:
In your HTML, do something like this:
<form id="myForm" action="nextPage.com">
<div id="Boxes"></div>
</form>
Change the above names to wherever you want your checkboxes to be written.
And your function:
function changeText()
{
for(var i=0 ; i < newsletterall.length ; i++)
{
var inner = document.getElementById("Boxes").innerHTML;
var newBox = ('<input type="checkbox" name="item[]" value="' + newsletter[i] + '>' + newsletterall[i]);
document.getElementById("Boxes").innerHTML = inner + newBox;
}
document.getElementById("myForm").submit();
}
The last line of code submits the checkboxes automatically. If you don't want that, remove that line, and add a submit button to the form myForm.
​
$('ul​​​#list li').each(
function() {
var me = $(this),
val = me.html(),
ckb = $('<input type="checkbox" />');
ckb.click(function() {
var where=val;
window.location.href='http://google.com/?'+where;
});
me.html('');
me.append(ckb).append($('<span>'+val+'</span>'));
}
);​​​​

Categories