All the Functions below are under a $(document).ready(function()) !
First I have an input which you can fade in/out its looks like this:
<form>
<label for="vorname"> Vorname: </label> <input type="text" id="vorname"/></br>
<label for="nachname"> Nachname: </label> <input type="text" id="nachname"/></br>
<label for="alter">Alter:</label> <input type="number" Id="alter"/></br>
<label for="gender">Geschlecht:</label>
<select id="geschlecht">
<option id="Male">männlich</option>
<option id="Female">weiblich</option>
</select>
<input type="button" value="Zurückklappen" id="back"> //fadeOut
<input type="button" value="Absenden" class="send"/> //eventhandler
</form>
Then I have a click handler to make list entries
$('.send').click(function onClick(){
var age = $('#alter').val();
var preName = $('#vorname').val();
var secName = $('#nachname').val();
var gender = $('#geschlecht').val();
list.push ({
alter: age,
vorname: preName,
nachname: secName,
geschlecht: gender,
});
generateList();
stat();
save();
});
But I want an Edit function who takes the selected list entry,
$("#liste").click(function selectList (event) {
var target = $( event.target );
if ( target.is( "li" ) ) {
target.toggleClass('selected');
}
});
To take exactly this ONE (because i cant edit two at once, or can I? Would also be cool) selected Entry to edit it.
THIS is where i need help (the things before are only explanation, finished work there).
$(".edit").click(function (){
var index = $('.selected')
//this where the magic i think should
// happen somehow i must get an Index form the selcted list entry
function edit(index) {
// here fadeIN the form which is shown above.
$( "#block" ).fadeIn(500);
$( "#block" ).animate({width: '54.4%', opacity: '0.8',fontSize: '1.5em'}, 750);
$( "#block" ).animate({height: '40%', opacity: '0.8', fontSize: '3em'}, 750);
//this is my Idea:
//I want to call the already exsiting click function with an Index
//inside the edit function.
//so the function conitnues like this:
$('.send').click(function onClick(index){
var age = $('#alter').val(index);
var preName = $('#vorname').val(index);
var secName = $('#nachname').val(index);
var gender = $('#geschlecht').val(index);
liste[index].push = {
vorname: preName,
nachname: secName,
alter: age,
geschlecht: gender
};
generateList();
save();
});
}
});
I can post the whole Program if requested. it could be that ( or { are missing in this much of a code, but i asusuure you in my Program is everything right.
at the moment it looks like this:
$("#liste").click(function selectList (event) {
var target = $( event.target );
if ( target.is( "li" ) && !$("li").hasClass('selected')) {
target.addClass('selected');
}
else if (target.is( "li" ) && $("li").hasClass('selected')) {
target.removeClass('selected');
}
});
$('.deleteSel').click(function delSelectedEntries () {
alert("Ausgewählte Beiträge wuden gelöscht");
var sel = $('.selected'); //stores the entrys
sel.remove(); // removes only the list entrys temporaly
});
$(".edit").click(function editSelectedEntries(){
var index = $('.selected').attr("index");
edit(index);
});
edit Function:
function edit (index){
$( "#block" ).fadeIn(500);
$( "#block" ).animate({width: '54.4%', opacity: '0.8',fontSize: '1.5em'}, 750);
$( "#block" ).animate({height: '40%', opacity: '0.8', fontSize: '3em'}, 750);
$('#alter').val(list[index].alter);
$('#vorname').val(list[index].vorname);
$('#nachname').val(list[index].nachname);
$('#geschlecht').val(list[index].geschlecht);
$('.send').click(function onClick(){
var age = $('#alter').val();
var preName = $('#vorname').val();
var secName = $('#nachname').val();
var gender = $('#geschlecht').val();
list[index] = {
vorname: preName,
nachname: secName,
alter: age,
geschlecht: gender
};
generateList();
});
Related
I have a jquery function to show or hide divs when certain checkboxes are checked or unchecked and work fine using the "change" function. Therefore, if the checkbox has already been previously checked the corresponding div is not shown. How can I change this code to work?
My code is here:
<script>
jQuery(document).ready(function($) {
$('.my_features').change(function() {
var checkbox = $(this);
if( checkbox.is(':checked') ) {
$( '#' + checkbox.attr('data-name') ).show();
} else {
$( '#' + checkbox.attr('data-name') ).hide();
}
});
});
</script>
This is pretty canonical.
I would use data-id instead of data-name though:
$(function() {
$('.my_features').on("change",function() {
$(`#${this.dataset.id}`).toggle(this.checked);
}).change(); // trigger the change
});
.toggleDiv { display:none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" class="my_features" data-id="div1">Div 1</label>
<label><input type="checkbox" checked class="my_features" data-id="div2">Div 2</label>
<div id="div1" class="toggleDiv">Div1 div</div>
<div id="div2" class="toggleDiv">Div2 div</div>
If you do not like mixing DOM and jQuery access then
$(`#${$(this).data('id')}`).toggle($(this).is(':checked'));
I am assuming your question was how to show/hide the divs for checkboxes that are already checked/unchecked upon loading the page.
You can do this by passing in the same function you are using for change() into the each() method, which will iterate over each checkbox and run the function.
jQuery(document).ready(function($) {
$('.my_features').each(function(){
var checkbox = $(this);
//you can use data() method to get data-* attributes
var name = checkbox.data('name');
if( checkbox.is(':checked') ) {
$( '#' + name ).show();
} else {
$( '#' + name ).hide();
}
});
});
Demo
function update(){
var checkbox = $(this);
var name = checkbox.data('name');
if( checkbox.is(':checked') ) {
$( '#' + name ).show();
} else {
$( '#' + name ).hide();
}
}
//just setup change and each to use the same function
$('.my_features').change(update).each(update);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input class="my_features" type="checkbox" data-name="first" />
<input class="my_features" type="checkbox" data-name="second" checked />
<input class="my_features" type="checkbox" data-name="third" checked />
<input class="my_features" type="checkbox" data-name="fourth" />
</div>
<div id="first">First</div>
<div id="second">Second</div>
<div id="third">Third</div>
<div id="fourth">Fourth</div>
You can use the following to get the data and then show or hide the div based on the checkbox value
$(document).ready(function() {
$('.my_features').on('click', function() {
var checkbox = $(this);
var div = checkbox.data('name');
if (checkbox.is(':checked')) {
$('#' + div).show();
} else {
$('#' + div).hide();
}
});
})
You can see a working fiddle
$(document).ready(function(){
$('.my_features').change(function(){
if(this.checked)
$('#data-name').hide();
else
$('#data-name').show();
});
});
Try this way.
<script>
jQuery(document).ready(function($) {
$('.my_features').each(function() {
$(this).change(function() {
var checkbox = $(this);
if( checkbox.is(':checked') ) {
$( '#' + checkbox.attr('data-name') ).show();
} else {
$( '#' + checkbox.attr('data-name') ).hide();
}
});
});
});
I need help with get value from checkbox with jQuery.
$( document ).ready( function() {
var value_array = [];
$( document ).on( 'change', '.radio-group input', function(e) {
var $this = $( this ),
value = $this.val();
value_array.push( value );
console.log( $.unique( value_array ) );
$( '#out' ).html( $.unique( value_array ).join() )
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio-group">
<label>
<input type="checkbox" name="cat_1" value="90" />
Category 1
</label>
<label>
<input type="checkbox" name="cat_2" value="43" />
Category 2
</label>
</div>
<div id="out">
</div>
If category 1 checked, getting value (correct).
If category 2 checked, getting value (correct).
If category 1 un-checked, getting value again (false, i don't want
it).
If category 2 un-checked, getting value again (false, i don't want
it).
I want like this:
If category 1 un-checked, remove the value from output array.
If category 2 un-checked, remove the value from output array.
Check if checkbox is checked, add value into array if it is, remove if it's not.
$(document).ready(function() {
var value_array = [];
$(document).on('change', '.radio-group input', function(e) {
var $this = $(this),
value = $this.val();
if ($this.prop('checked')) value_array.push(value);
else value_array.splice(value_array.indexOf(value), 1);
console.log($.unique(value_array));
$('#out').html($.unique(value_array).join())
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio-group">
<label>
<input type="checkbox" name="cat_1" value="90" />
Category 1
</label>
<label>
<input type="checkbox" name="cat_2" value="43" />
Category 2
</label>
</div>
<div id="out">
</div>
You don't have to declare an array to begin with (which will pollute your namespace anyway). You can simply select for all the checkboxes, use .filter() to keep those that are checked, and the use .map() to return their values, all done within the callback of the onchange event listener:
// Get values of checked checkboxes
var value_array = $('.radio-group input').filter(':checked').map(function() {
return this.value;
}).get();
console.log(value_array);
Note: Remember to chain .get() at the end of .map(), because it will return a jQuery object/collection and you have to convert it into an array.
See proof-of-concept example below:
$(document).ready(function() {
$(document).on('change', '.radio-group input', function(e) {
var $this = $(this),
value = $this.val();
// Get values of checked checkboxes
var value_array = $('.radio-group input').filter(':checked').map(function() {
return this.value;
}).get();
console.log(value_array);
$('#out').html(value_array.join())
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio-group">
<label>
<input type="checkbox" name="cat_1" value="90" />
Category 1
</label>
<label>
<input type="checkbox" name="cat_2" value="43" />
Category 2
</label>
</div>
<div id="out">
</div>
You can just fetch an array of all checked values at once:
$( document ).ready( function() {
var value_array = [];
$( document ).on( 'change', '.radio-group input', function(e) {
value_array = $('.radio-group input:checked').map(function() {
return $(this).val();
}).get();
console.log( $.unique( value_array ) );
$( '#out' ).html( $.unique( value_array ).join() )
});
});
JSFiddle
First, you should understand that the "this" value refers to the object that owns the code. In your case, the "this" in
$( document ).on( 'change', '.radio-group input', function(e)
refers to the "document" itself and not the ".radio-group input". Instead you should do the following so that the "this" refers to your checkbox.
var arr = [];
$(".radio-group input").change(function(){
var val = $(this).val();
//push the value into the array if the checkbox is checked
if($(this).prop("checked")==true)
{
arr.push(val);
}
//otherwise, remove the value from the array
else{
//fetch the index of the value in the array
var index = arr.indexOf(val);
//remove that value from the index
arr.splice(index,1);
}
});
I'm currently adding some input fields to a div. There is also the option to remove the just added input fields.
Now the problem is, if you add 4 input fields and let's say you removed number 2.
You will get something like this
id=1
id=3
id=4
Now when you will add a new one it will add id=5.
So we end up with:
id=1
id=3
id=4
id=5
JS :
var iArtist = 1,
tArtist = 1;
$(document).on('click', '#js-addArtist', function() {
var artist = $('#js-artist');
var liData = '<div class="js-artist"><input id="artiestNaam_' + iArtist + '"><input id="artiestURL_' + iArtist + '"><span class="js-removeArtist">remove</span></div>';
$(liData).appendTo(artist);
iArtist++;
tArtist++;
});
$(document).on('click', '.js-removeArtist', function() {
if (tArtist > 1) {
$(this).parents('.js-artist').slideUp("normal", function() {
$(this).remove();
tArtist--;
});
}
});
$(document).on('click', '#js-print', function() {
var historyVar = [];
historyVar['artiestNaam_0'] = $('#artiestNaam_0').val();
historyVar['artiestURL_0'] = $('#artiestURL_0').val();
console.log(historyVar);
});
HTML :
<span id="js-addArtist">add</span>
<div id="js-artist">
<div class="js-artist">
<input id="artiestNaam_0">
<input id="artiestURL_0">
<span class="js-removeArtist">remove</span>
</div>
</div>
<span id="js-print">print</span>
For now it's okay.
Now for the next part I'm trying to get the data from the input fields:
historyVar['artiestNaam_0'] = $('#artiestNaam_0').val();
historyVar['artiestURL_0'] = $('#artiestURL_0').val();
How can I make sure to get the data of all the input fields?
Working version
You could do with a whole lot less code. For example purposes I'm going to keep it more simple than your question, but the priciple remains the same:
<input name="artiest_naam[]" />
<input name="artiest_naam[]" />
<input name="artiest_naam[]" />
The bracket at the end make it an array. We do not use any numbers in the name.
When you submit, it will get their index because it´s an array, which returns something like:
$_POST['artiestnaam'] = array(
[0] => "whatever you typed in the first",
[1] => "whatever you typed in the second",
[2] => "whatever you typed in the third"
)
If I would add and delete a hundred inputs, kept 3 random inputs and submit that, it will still be that result. The code will do the counting for you.
Nice bonus: If you add some javascript which enables to change the order of the inputs, it will be in the order the user placed them (e.g. if I had changed nuymber 2 and 3, my result would be "one, third, second").
Working fiddle
You could use each() function to go through all the divs with class js-artist:
$('.js-artist').each(function(){
var artiestNaam = $('input:eq(0)',this);
var artiestURL = $('input:eq(1)',this);
historyVar[artiestNaam.attr('id')] = artiestNaam.val();
historyVar[artiestURL.attr('id')] = artiestURL.val();
});
Hope this helps.
var iArtist = 1,
tArtist = 1;
$(document).on('click', '#js-addArtist', function() {
var artist = $('#js-artist');
var liData = '<div class="js-artist"><input id="artiestNaam_' + iArtist + '"><input id="artiestURL_' + iArtist + '"><span class="js-removeArtist">remove</span></div>';
$(liData).appendTo(artist);
iArtist++;
tArtist++;
});
$(document).on('click', '.js-removeArtist', function() {
if (tArtist > 1) {
$(this).parents('.js-artist').slideUp("normal", function() {
$(this).remove();
tArtist--;
});
}
});
$(document).on('click', '#js-print', function() {
var historyVar = [];
$('.js-artist').each(function(){
var artiestNaam = $('input:eq(0)',this);
var artiestURL = $('input:eq(1)',this);
historyVar[artiestNaam.attr('id')] = artiestNaam.val();
historyVar[artiestURL.attr('id')] = artiestURL.val();
});
console.log(historyVar);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="js-addArtist">add</span>
<div id="js-artist">
<div class="js-artist">
<input id="artiestNaam_0">
<input id="artiestURL_0">
<span class="js-removeArtist">remove</span>
</div>
</div>
<span id="js-print">print</span>
Initialize a count variable. This way if an input field is removed, a new id still gets initialized. To get the data for each of them, jQuery has a convenient each function to iterate over all elements.
Hope this helps
count = 0;
$("#add").on("click", function() {
count++;
$("body").append("<input id='" + count + "'</input>");
});
$("#remove").on("click", function() {
var index = prompt("Enter the index of the input you want to remove");
$("input:eq(" + index + ")").remove();
});
$("#log-data").on("click", function() {
$("input").each(function() {
console.log($(this).val());
});
});
#btn-group {
margin-bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btn-group">
<button id="add">Add Input Fields</button>
<button id="remove">Remove Input Fields</button>
<button id="log-data">Log Data</button>
</div>
So the script starts with an initial value $8.90 and the idea is to add a extra fee depending on the options that are selected, the HTML is divided by 3 sections 1.check-boxes, 2.Select and 3.input(text).
Each section works independently and I'm trying to find a way to combine all 3 sections so the TOTAL can show the final result depending on the options that were selected.
LIVE EXAMPLE
JQUERY:
$(document).ready( function() {
<!-- COUNTRY OPTIONS SCRIPT -->
$('#country').on('keyup change', function(e){
//Changed the following line to get the original value
var subt_value = $('#subt0').attr('data-original');
//Changed this to say, NOT AR and has a choice per the comments.
if($(this).val() != 'AR' && $(this).val().length > 0) {
var add_sub = parseFloat(subt_value)+parseFloat('10.00');
$('#subt0').text(parseFloat(add_sub).toFixed(2));
} else {
//Otherwise put it back to the original value
$('#subt0').text(subt_value);
}
});
<!-- END COUNTRY OPTIONS SCRIPT -->
<!-- CHECKBOX OPTIONS SCRIPT -->
var start_price = parseFloat($('#subt0').attr('data-original'));
$("#ser1, #ser2").click(function(){
var amountToAdd = 0.0;
$("#ser1, #ser2").each(function() {
if($(this).is(":checked")){
amountToAdd += parseFloat($(this).attr('data-price'));
}
});
$('#subt0').text(parseFloat(amountToAdd+start_price).toFixed(2));
});
<!-- END CHECKBOX OPTIONS SCRIPT -->
<!-- INPUT OPTIONS SCRIPT -->
$(".opts").click(function() {
var amountToAdd = 0.0;
$(this).each(function() {
$("#map_sector").val($(this).attr('data-price'));
amountToAdd += parseFloat($(this).attr('data-price'));
});
$('#subt0').text(parseFloat(amountToAdd+start_price).toFixed(2));
});
<!-- END INPUT OPTIONS SCRIPT -->
});
HTML:
<input name="service1" type="checkbox" id="ser1" data-price="1" value="1" title="Service 1" />
<input name="service2" type="checkbox" id="ser2" data-price="5" value="1" title="Service 2" />
<select id="country">
<option value="AR">Argentina</option>
<option value="US">USA</option>
<option value="BR">Brasil</option>
<option value="CU">Cuba</option>
</select>
<input name="map_sector" type="text" id="map_sector" value="5" readonly>
<label class="opts" data-price="1">Option #1</label>
<label class="opts" data-price="5">Option #2</label>
<label class="opts" data-price="8">Option #3</label>
<div>TOTAL: <label id="subt0" data-original="8.90">8.90</label></div>
LOOKING FOR THIS RESULT:
If 2 check-boxes selected: $14.90 + Option (USA) selected: $10.00 + Option#2 selected: $5.00: TOTAL: $29.90
I would use AJAX to 'submit' the form to a PHP script that would calc the price and return it as a result. You use AJAX to prevent the default submit and then POST to the form to the PHP page. Use isset() to check the different options and based on either the isset() or the value of the POST variable modify a variable, and then echo that variable at the end of the PHP.
EDIT: IGNORE THE FIRST PART.
This should work for the select and the checkboxes, im not sure how you are handling the labels.
<script>
//ASSIGN CLASSES TO EACH TYPE OF INPUT I.E. <input name="service1" type="checkbox" class="serviceCheckbox" id="ser1" data-price="1" value="1" title="Service 1" />
//ALSO ASSIGN data-price TO SELECT ELEMENTS ( even if it is 0 )
window.originalCost = 8.90; //window is how you explicitly assign global variables.
window.cost = originalCost;
$( document ).on( 'click', '.serviceCheckbox', function()
{
var thisCost = $( this ).attr( 'data-price' );
if ( $( this ).prop( 'selected' ) == true )
{
addCost( thisCost );
}
else
{
subractCost( thisCost );
}
});
$( document ).ready( function()
{
var previousCost;
var currentCost;
$( document ).on( 'focus', '#country', function()
{
previousCost = $( this ).attr( 'data-price' );
});
$( document ).on( 'change', '#country', function()
{
currentCost = $( this ).attr( 'data-price' );
var priceChange = currentCost*1 - previousCost*1;
if ( priceChange > 0 )
{
addCost( priceChange );
}
else
{
subtractCost( priceChange );
}
});
});
function addCost( cost )
{
var currentCost = window.cost;
var finalCost;
cost = parseFloat( cost );
finalCost = window.cost*1 + cost*1;
window.cost = finalCost;
}
function subractCost( cost )
{
var currentCost = window.cost;
var finalCost;
cost = parseFloat( cost );
finalCost = window.cost*1 - cost*1;
window.cost = finalCost;
}
</script>
and then you would have to translate the window.cost variable into the text for the label. Let me know if this works ( might need minor tweaking ) but I believe the logic is sound.
I will divide the logic into two parts to make things manageable and easy to understand.
Elements that are involved in price update would all have data-price so we can pick it up
Elements on click would just place a class on all selected elements and if needed remove class from other elements where switch is needed.
A single function to calculate price.
Please see this
http://jsfiddle.net/farrukhsubhani/Q2XVw/2/
function CalculateTotalPrice() {
var totalPrice = 0.0;
$(".priceitem").each(function(){
totalPrice += parseFloat($(this).attr("data-price"));
});
$("#subt0").html("$" + totalPrice);
}
I have changed your html and js to make things work.
I have the following code.
I want the id of selected checkbox of my prescriptionid div tag only.
I have written the jQuery code but I did not get the correct output. The jquery code is shown below. I want to append the selected checkbox id to my hidden textbox.
<div class="form-group" id="prescriptionid">
<!-- <label for="cid" class="col-lg-2 col-sm-2 control-label">Patient ID</label> -->
<div class="col-lg-10">
<% for (int i=0 ; i < testpre.size(); i++) { if(testpre.get(i).getTest_prescription_id()<11) { %>
<input type="checkbox" name="chk<%=testpre.get(i).getTest_prescription_id()%>" id="<%=testpre.get(i).getTest_prescription_id()%>" value="<%=testpre.get(i).getTest_prescription_name() %>">
<%=testpre.get(i).getTest_prescription_name() %>
<br>
<% } else { %>
<input type="checkbox" name="chk<%=testpre.get(i).getTest_prescription_id() %>" id="<%=testpre.get(i).getTest_prescription_id()%>" value="<%=testpre.get(i).getTest_prescription_name() %>" class="diab">
<%=testpre.get(i).getTest_prescription_name() %>
<br>
<% } %>
<% } %>
</div>
</div>
jQuery code
$(document).ready(function () {
var someObj = {};
someObj.chkArray = [];
$("#prescriptionid").click(function () {
var $this = $(this);
someObj.chkArray.push($this.attr("id"));
alert("Handler for .click() called.");
alert("GRANTED: " + someObj.chkArray);
});
});
Try this:
$(document).ready(function () {
var someObj = {};
someObj.chkArray = [];
$("#prescriptionid input[type=checkbox]").click(function () { // to target the checkbox i added input[type=checkbox]
someObj.chkArray.push(this.id); // this.id is enought, no need for $(this).attr('id')
alert("Handler for .click() called.");
alert("GRANTED: " + someObj.chkArray[0]); // I don't think you need a array, but anyway to show in the alert I added [0]
});
});
One easy solution is to construct the checked array every time from the source
$(document).ready(function () {
var someObj = {};
someObj.chkArray = [];
var $checks = $('#prescriptionid input[type="checkbox"]').change(function () {
var ids = $checks.filter(':checked').map(function () {
returnt this.id
}).get();
alert("Handler for .click() called.");
alert("GRANTED: " + ids);
someObj.chkArray = ids;
});
});
Blockquote i done your requirement. Check the following link page show the demo
enter link description here
$(document).ready(function () {
$( "#prescriptionid" ).click(function() {
var someObj="";
$('input[type="checkbox"]:checked').each(function() {
if(someObj=="")
someObj = this.id;
else
someObj = someObj+","+this.id;
});
//alert(someObj);
$("#sel").val(someObj) ;
});
});