I found this example:
The Idea is to get the checked checkbox value, and use it further as avariable:
Maybe this example is not the best, but I only found this one as it is much closer to what I want.
See FIDDLE
<div id="pakker">
<input type="checkbox" checked="checked" value="39" />test 1<br/>
<input type="checkbox" value="79" />test 2<br/>
<input type="checkbox" value="29" />test 3<br/>
<input type="checkbox" value="49" />test 4<br/>
<script type="text/javascript">
jQuery(document).ready(function($) {
var sum = 0;
$('#pakker :checkbox').click(function() {
sum = 0;
$('#pakker :checkbox:checked').each(function(idx, elm) {
sum += parseInt(elm.value, 10);
});
$('#sum').html(sum);
});
});
</script>
As you can see it shows values only after mouse click checkbox. How can I make it to get the checked checkbox value on Loading page? Example: http://jsfiddle.net/vaKWs/31/
if more then one checkbox is selected it ADDS the numbers. is it possible to show the valuse like (93, 25, 256 etc) without adding them?
Is it possible the result to put into a VARIABLE so that i can use this variable in other functions on the page? For example if $variable { then } esle {...
* PS * I am new with php and js. Thank you for understanding!
jQuery(document).ready(function($) {
var sum = 0;
$('#pakker :checkbox').click(function() {
sum = 0;
$('#pakker :checkbox:checked').each(function(idx, elm) {
sum += parseInt(elm.value, 10);
});
$('#sum').html(sum);
});
$('#pakker :checkbox[checked]').each(function(idx, elm){
sum += parseInt(elm.value, 10);
});
$('#sum').html(sum);
});
in HTML:
<input type="checkbox" checked value="39" />test 1<br/>
http://jsfiddle.net/vaKWs/6/
There you go.
Please rate my answer.
that would really help me!!
already answered
You use a sum of the values, if you want them as separate text: sum += parseInt(elm.value, 10) + " " should do it. This forces a space between keeping them as a text string.
The example you have saves them into a variable already. Check out arrays for storing them into individual variables
Hope that helps
Actually #Jose makes a lot of sense to me.
i felt exactly like you before. but with of a lot of learning i manage to create nice sites.
let me help you on 3:
if you assign a varible at the top of the page like that HTML:
<script>
myNewVar = new Array();
//... rest of the script
</script>
so that variable is available to all scripts around..
Related
I would like implement on my own website this kind of search box - http://www.chippmunk.com/.
(under Savings Start Here)
How this works with a sliding horizontal input & 2 other inputs, one of which having a dropdown effect? i would like to know how all these things are combined to search.
Do you know some tutorials for this or could you help me to build?
Thank you so much in advance.
Based on Vlad Preda's comment, I got a code and edited it slightly to create a slider function which gives me a variable ( say range 23 to 109), which answers part of my question.
<div>
<input id="cost" name="cost" type="range" min=23 max=109 value=93 style="width: 40%;">
<output for="cost">1</output>
</div>
Now I would require to use this as an input, along with another input (an string. e.g. a store name)
How would I manage to combine these two elements to give me a proper search results?
JavaScript code -
$(function() {
var el, newPoint, newPlace, offset;
$("input[type='range']").change(function() {
el = $(this);
width = el.width();
newPoint = (el.val() - el.attr("min")) / (el.attr("max") - el.attr("min"));
offset = -1.3;
if (newPoint < 0) { newPlace = 0; }
else if (newPoint > 1) { newPlace = width; }
else { newPlace = width * newPoint + offset; offset -= newPoint;}
el
.next("output")
.text(el.val());
})
.trigger('change');
});
I guess there is a variable e1.val() which has got the updated value, I would need to combine this with another input and pass both parameters to the search variable.
I'm looking to create a pretty simple calculator, but I need it to update on each keystroke. I cannot seem to find anything in that specific category. Can anyone point me to the right direction?
I'm looking for something like A*1.325 + B*3.76 where B is a drop down menu and A is the text field that people will be filling out. Every time the drop down is changed or a keystroke is registered in the text box.
I will also try to do some RegEx to only allow numbers or decimal points!
Thank you guys very much!!!
PS. Will be using PHP/HTML to create the form.
Step 1:
Do the jQuery tutorials. fun fun fun :D :D :D
http://docs.jquery.com/Tutorials
Step 2:
Now that you understand jQuery, notice that jQuery supports a bunch of event handlers. For instance, you can assign a click event to something that resembles an item in a dropdown menu:
$("itemInMyDropDownMenu").click(function(e) {
doSomeCalculation(parseFloat(this.val()));
}
Step 3:
Chose the right event handlers to use. click (for the dropdown menu) and keyup (for the text field) sound hopeful.
Step 4:
Keep tinkering. You don't need PHP at all.
The first question. If you need just simple calculator, why would you need AJAX? AJAX can send requests to web pages and scripts and get the XML, JSON, html or simple text responses.
If you still need AJAX, read http://www.w3schools.com/ajax/default.asp
Realtime updates:
Set the id of elements you are going to work with.
Create the appropriate handler, which is called any time the field is changed.
<input type="text" id="field" value="" onChange="javascript: setA(this)"/>
function setA(obj){
var a = 0 ;
if (obj.value)
a = obj.value ;
//call any function to calculate anything and send a.
}
If you want to display something, here id comes to be handy.
<div id="result"></div>
document.getElementById("result").innerHTML = 345 ; //just set to what you need
You can fully utilize javascript for building simple calculator without submitting the form, as it can work in real time.
Hope it helps :)
While I waiting to hear back I did a little more research and found some code that I think will work for what I was looking for. I was overthinking the whole thing!!
<html>
<head>
</head>
<body>
<script>
function doMath() {
var totalparts = parseInt(document.getElementById('parts_input').value);
var labor = parseInt(document.getElementById('labor_input').value);
var misc = parseInt(document.getElementById('misc_input').value);
var subtotal = totalparts + labor + misc;
var tax = subtotal * .13;
var total = subtotal + tax;
document.getElementById('subtotal_input').value = subtotal;
document.getElementById('tax_input').value = tax;
document.getElementById('total_input').value = total;
}
</script>
<div>Total Parts: <input type="text" id="parts_input" value="1" readonly="true" /></div>
<div>Labor: <input type="text" id="labor_input" onBlur="doMath();" /></div>
<div>Misc: <input type="text" id="misc_input" onBlur="doMath();" /></div>
<div>Sub Total: <input type="text" id="subtotal_input" readonly="true" /></div>
<div>Tax: <input type="text" id="tax_input" readonly="true" /></div>
<div>Total: <input type="text" id="total_input" readonly="true" /></div>
</body>
</html>
You don't need to use, and shouldn't use, AJAX for this. Instead, you should do something like this:
$("#textfieldID, #dropDownMenuID").change(function() {
var aVal = $("#textFieldID").val() == "" ? 0 : parseFloat($("#textFieldID").val());
var bVal = $("#dropDownMenuID").val() == "" ? 0 : parseFloat($("#dropDownMenuID").val());
$("#answerID").text((aVal*1.325 + bVal*3.76).toString());
});
Have you tried onchange="calculator()"?
Trying to make the infamous checkall checkbox for dynamically created rows from a MySQL query. Rows (and therefore checkboxes) could range from 1 row to a metric buttload.
The form (without the checkall) is as follows:
<form name="form" method="post" action = "process.order.php">
<?php
while($fetch = mysql_fetch_array($order_query){
$order_id = $fetch['oid'];
$order_status = $fetch['ostat'];
?>
<input type="checkbox" name="order_row[<?=$order_id?>]" id="1" value="1">
<select name="status[<?=$order_id?>]" id="status[<?=$order_id?>]"
<option value="Ordered">Ordered</option>
<option value="Backordered">Backordered</option>
</select>
<? } ?>
<input type="submit" name="submit" id="submit" value="submit"> </form>
In process.order.php:
<?php
if(is_array($order_row)){
foreach($order_row as $order_id=>$val){
...followed by the rest of the script. I tried using this: How to implement "select all" check box in HTML?
and this:
Select All Checkbox
I'm trying to avoid using jQuery at this moment. Is there a way I can call the checkbox name generated by the PHP script into the javascript code?
Update:
I'd like to use a function that I can call across multiple pages. Thus, calling embedding the form name in the JS won't be practical for me. Also, I'd like it to be a checkbox - the button's worked great, but I'm trying to keep the UI simple and I already have a lot of buttons I'm trying to get rid of...
Working Example
You can do like this:
var frm = document.forms['form'];
for (var i = 0, l = frm.elements.length; i < l; i++) {
if (frm.elements[i].type === 'checkbox') {
frm.elements[i].checked = true;
}
}
Similarly, to uncheck all set:
frm.elements[i].checked = true;
to false.
You can also easily create checkAll and unCheckAll functions using above code.
By the way, an id with only numeric value is invalid, you should use alpha or mix of alpha and numeric characters.
If you don't have to support IE6 or 7, the following will work.
Live Demo
var checkAll = document.getElementById("checkall");
checkAll.onclick = function(){
[].forEach.call(
document.forms['form'].querySelectorAll("input[type='checkbox']"),
function(el){
el.checked=true;
});
}
I've referred to this post:
Post array of multiple checkbox values
And this jQuery forum post:
http://forum.jquery.com/topic/checkbox-names-aggregate-as-array-in-a-hidden-input-value
I am trying to collect an array (or concatenated string with commas, whatever) of checkbox values in a hidden input field using jQuery. Here's the script code I'm using:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val(function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
});
});
</script>
A snippet of the relevant HTML:
<form id="advancedSearchForm" name="advancedSearchForm" method="post" action="<?php echo site_url('/magcm/advancedSearch#results'); ?>">
<input type="checkbox" name="FCM" id="FCM" class="chk" value="FCM" <?php echo set_checkbox('FCM', 'FCM'); ?>/>
<input type="hidden" name="specialty" id="specialty" value="" />
<input class="button" name="submit3" id="submit3" type="submit" value="Search" />
I've tried changing "submit" to "submit3" in the jQuery, which breaks (obviously). When I print_r($_POST), the checkboxes POST correctly but the condensed hidden variable does not. (It posts, but a blank value.) The checkboxes persist correctly using CI's hacked set_value() function (Derek needs to implement this in the main trunk... but that's another story)
I'm sure I'm doing something that is wrong and easy to point out. I've just been banging my head against the wall for the past 2 hours on it, trying various functions and changing a ton of things and analyzing it in Chrome dev tools (which don't show any errors).
Help is appreciated. :)
Let's say you applied an class, maybe "tehAwesomeCheckboxen" to every checkbox. Then
<script>
$("#advancedSearchForm").submit(function() {
var chkbxValues = $(".tehAwesomeCheckboxen").val();
$("#specialty").val( chkbxValues.join(",") );
});
</script>
EDIT:
I don't think the $_POST array is getting populated, since the submit is being handled locally by the JavaScript engine. SO... let's try this:
<script>
var chkbxValues = new Array();
$(".tehAwesomeCheckboxen").live("change", function(e){
var val = $(this).val();
if( $(this).is(":checked") ) {
if( chkbxValues.length == 0 || chkbxValues.indexOf(val) == -1){
// Add the value
chkbxValues.push(val);
}
}
else {
// remove the value
chkbxValues.splice( chkbxValues.indexOf(val), 1 );
}
$("#specialty").val( chkbxValues.join(",") );
});
</script>
This adds an event handler the checkboxes themselves, such that checking/unchecking the box alters the hidden element. Then your form handles its submission as normal.
Is this more in line with what you're trying to do?
P.S. Those who upvoted this, please note I have modified my answer. Please verify whether you still find it useful and adjust your vote accordingly.
I ended up solving it using PHP arrays rather than jQuery:
<input type="checkbox" name="chk[]" id="RET" class="chk" value="RET" <?php echo set_checkbox('chk', 'RET'); ?>/>
I changed the name to an array and POSTed it to my script, where I looped through the array and handled it there. Still not sure what the problem was with the jQuery-based solutions, but I figured I'd post this for everyone to refer to in the future.
You've got lots of nested functions() in your JavaScript, makes it hard to follow what you're doing.
However, it seems that you're just passing a function to .val() rather than an actual value. Try this instead:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val((function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
})());
});
</script>
Or even better, calculate the value first:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
var value = $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
$(form).find("input[name=specialty]").val(value);
});
</script>
I am using a checkbox that has the name as "selectedids[]" and I am trying to select all checkboxes with the JavaScript. The code is not working. When I change the name of the checkbox to "selectedids" it works, but I can't do so because I need all the ids that are selected on the POSTED page.
The checkbox is as follows:
foreach($rows as $row)
{
<input type="checkbox" name="selectedids[]" value="<?php echo $row['id']; ?>" class="checkbox" />
........
........
}
And the Java-script function is as follows:
function SetAllCheckBoxes(CheckValue)
{
var CheckValue=true;
if(!document.forms['main'])
return;
var objCheckBoxes = document.forms['main'].elements['selectedids[]'];
if(!objCheckBoxes)
return;
var countCheckBoxes = objCheckBoxes.length;
if(!countCheckBoxes)
objCheckBoxes.checked = CheckValue;
else
// set the check value for all check boxes
for(var i = 0; i < countCheckBoxes; i++)
objCheckBoxes[i].checked = CheckValue;
}
Please help me......
Thanks in advance.......
Do you have the option to use jQuery? If so, then you could do something like:
$(':checkbox').each(function(){
$(this).attr('checked',true);
});
It also might work to try:
$(':checkbox').attr('checked',true);
Or, if you just want to make sure all the boxes are checked only when the page first loads you could have your php that creates the checkboxes include "CHECKED". i.e.
<input type='checkbox' name='selectedids[]' value='value' CHECKED>
Updated to use :checkbox per comment
Why don't you just select them by id?
e.g.
var a=0;
while(document.getElementById('mycheckbox_'+a))document.getElementById('mycheckbox_'+a).checked=true;
If it was me, I would use the class of the checkboxes to identify them, with a bit of jQuery.
This would work:
$('input.checkbox').each(function(){$(this).attr('checked',true); });
It would set all checkboxes with class "checkbox" as true.
Beaten to it!