I have the following code in my functions.php file, however the script does not seem to be doing what it is intended to do.
My plus and minus buttons have classes .plus and my .minus respectively.
PHP / JQuery :
/*
========================================
Change qty by step on button click
========================================
*/
function kia_add_script_to_footer(){ ?>
<script>
jQuery(document).ready(function(){
jQuery(document).on('click', '.plus', function(e) { // replace '.quantity' with document (without single quote)
$input = jQuery(this).siblings('.quantity .qty');
var val = parseInt($input.val());
var step = $input.attr('step');
step = 'undefined' !== typeof(step) ? parseInt(step) : 0.5;
$input.val( val + step ).change();
});
jQuery(document).on('click', '.minus', // replace '.quantity' with document (without single quote)
function(e) {
$input = jQuery(this).siblings('.quantity .qty');
var val = parseInt($input.val());
var step = $input.attr('step');
step = 'undefined' !== typeof(step) ? parseInt(step) : 0.5;
if (val > 0) {
$input.val( val - step ).change();
};
});
});
</script>
<?php };
add_action( 'wp_footer', 'kia_add_script_to_footer' );
Any help would be greatly appreciated!
EDIT: Apologies for the bland question. I have erased the generic input arrows for input.qty and added two buttons (.minus and .plus). What is meant to happen, is that on click of either .minus or .plus, the input.qty number should decrease or increase by var step amount.
As for the question of whether .qty is nested inside of .quantity, that would be correct. I was not sure if maybe .qty was being used elsewhere, so to confirm my coding was correct, I added the parent element's class.
HTML :
<div class="quantity">
<input class="minus" value="-" type="button">
<input class="input-text qty text" step="0.5" min="0.5" max="10" name="quantity" value="0" title="Qty" size="4" pattern="[0-9]*" inputmode="numeric" type="number">
<input class="plus" value="+" type="button">
<span>press - or + to add/remove meterage per half meter</span>
</div>
You need to use parseFloat() instead of parseInt()
Note: I've changed
step = 'undefined' !== typeof(step) ? parseInt(step) : 0.5;
to
step = step != null ? parseFloat(step) : 0.5;
only in the "plus function" to show another way how you could check the value.
jQuery(document).ready(function(){
jQuery(document).on('click', '.plus', function(e) {
$input = jQuery(this).siblings('.quantity .qty');
var val = parseFloat($input.val());
var step = $input.attr('step');
step = step != null ? parseFloat(step) : 0.5;
$input.val( val + step );
});
jQuery(document).on('click', '.minus', // replace '.quantity' with document (without single quote)
function(e) {
$input = jQuery(this).siblings('.quantity .qty');
var val = parseFloat($input.val());
var step = $input.attr('step');
step = 'undefined' !== typeof(step) ? parseFloat(step) : 0.5;
if (val > 0) {
$input.val( val - step ).change();
};
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="quantity">
<input class="minus" value="-" type="button">
<input class="input-text qty text" step="0.5" min="0.5" max="10" name="quantity" value="0" title="Qty" size="4" pattern="[0-9]*" inputmode="numeric" type="number">
<input class="plus" value="+" type="button">
<span>press - or + to add/remove meterage per half meter</span>
</div>
And here the same with less code and with always one decimal place see comments.
var round = function (value, precision) {
var multiplier = Math.pow(10, precision || 0);
return Math.round(value * multiplier) / multiplier;
}
jQuery(document).on('click', '.plus, .minus', function(e) {
var $input = jQuery(this).siblings('.quantity .qty');
var val = parseFloat($input.val());
var step = parseFloat($input.attr('step'));
step = step == null ? 0.5 : step;
var sum = val + step;
if($(this).hasClass('minus')) {
sum = val - step;
}
$input.val(sum.toFixed(1));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="quantity">
<input class="minus" value="-" type="button">
<input class="input-text qty text" step="0.5" min="0.5" max="10" name="quantity" value="0" title="Qty" size="4" pattern="[0-9]*" inputmode="numeric" type="number">
<input class="plus" value="+" type="button">
<span>press - or + to add/remove meterage per half meter</span>
</div>
Related
While on change i want to change the span values. Please check the below code.
Getting the values from databases using php
<input type="text" name="no_guest_conferance" class="conf_guest" id="no_guest_conferance" placeholder="Enter no. of guest" value ="<?php if(isset($con_details[0]['min_seating_capacity'])){echo $con_details[0]['min_seating_capacity'];}?>"/>
<span style="float:left; margin-bottom:14px;" id="conference_subtotal">
<span id="conferencesubtotal"><?php echo 'Rs. '.number_format(ceil($subTotal),0); ?> </span>
<span style="font-size:12px;" >Sub Total</span>
</span>
Script here.
<script>
$(document).ready(function(){
$("input").change(function(){
var val=$(this).val();
var price=$('#price').val();
var subtotal=val*price;
$("#conferencesubtotal").val(subtotal);
});
});
</script>
I didn't get the value here?please tell me where i mistake.
Use blur instead of change and to print value in span use text or html instead of the val, val will work for input only.
<script>
$(document).ready(function(){
$(".conf_guest").blur(function(){
var val=$(this).val();
var price=$('#price').val();
var subtotal=val*price;
$("#conferencesubtotal").text(subtotal);
});
});
</script>
Change the following line:
$("#conferencesubtotal").val(subtotal);
to
$("#conferencesubtotal").text(subtotal);
because span tag do not have a value attribute in it. The value it shows is its text, so provide your value in text()
On span use text() not val() and apply onchange event only on your Guest conference number field like,
$("input#no_guest_conferance").change(function() {
var val = Number(this.value);
var price = Number($('#price').val());
var subtotal = val * price;
$("#conferencesubtotal").text(subtotal);
});
$(document).ready(function() {
$("input#no_guest_conferance").change(function() {
var val = Number(this.value);
var price = Number($('#price').val());
var subtotal = val * price;
$("#conferencesubtotal").text(subtotal);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" name="no_guest_conferance" class="conf_guest" id="no_guest_conferance" placeholder="Enter no. of guest" value="1" />
<input type="text" name="price" class="conf_guest" id="price" placeholder="Price" value="10" disabled="disabled"/>
<span style="float:left; margin-bottom:14px;" id="conference_subtotal">
<span id="conferencesubtotal"></span>
<span style="font-size:12px;">Sub Total</span>
</span>
you can get the value from
$("#conferencesubtotal").html(subtotal);
.val() work only on input, select and textarea. jquery .val() doc
i dont want to use serialize() function please help me with this. I am a beginner
html
<input type='button' value='Add Tier Flavor' id='Add'>
<input type='button' value='Remove Tier Flavor' id='Remove'>
<div id='batch'>
<div id="BatchDiv1">
<h4>Batch #1 :</h4>
<label>Flavor<input class="textbox" type='text' id="fl1" name="fl[]" value=""/></label></br>
<label>Filling<input class="textbox" type='text' id="fi1" name="fi[]" value="" /></label></br>
<label>Frosting<input class="textbox" type='text' id="fr1" name="fr[]" value=""/></label></br>
</div>
</div>
<br>
</div>
this is a dynamically added fields using javascript the code is:
javascript
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#Add").click(function () {
if(counter>5){
alert("Only 5 Tiers allow");
return false;
}
var newBatchBoxDiv = $(document.createElement('div')).attr("id", 'BatchDiv' + counter);
newBatchBoxDiv.html('<h4>Batch #'+ counter + ' : </h4>' +
'<label> Flavor<input type="text" name="fl[]" id="fl' + counter + '" value=""></label><br>'+
'<label> Filling<input type="text" name="fi[]" id="fi' + counter + '" value=""></label><br>'+
'<label> Frosting<input type="text" name="fr[]" id="fr' + counter + '" value=""></label><br>' );
newBatchBoxDiv.appendTo("#batch");
counter++;
});
$("#Remove").click(function () {
if(counter==1){
alert("No more tier to remove");
return false;
}
counter--;
$("#BatchDiv" + counter).remove();
});
});
</script>
i am trying to post the values in an array to post it onto next .php page
i am using this
var user_cupfl = $('input[name^="fl"]').serialize();
var user_cupfi = $('input[name^="fi"]').serialize();
var user_cupfr = $('input[name^="fr"]').serialize();
serialize is not passing the values. :(
on second page i am trying to mail it using
$message .= "<tr><td><strong>Cake Flavors(according to batches):</strong> </td><td><pre>" .implode("\n", $user_cupfl). "</pre></td></tr>";
$message .= "<tr><td><strong>Filling type (Inside the cake):</strong> </td><td><pre>" .implode("\n", $user_cupfi). "</pre></td></tr>";
$message .= "<tr><td><strong>Frosting type (top of the cake):</strong> </td><td><pre>" .implode("\n", $user_cupfr). "</pre></td></tr>";
i m posting array like this
$user_cupfl=filter_var($_POST["userCupfl"], FILTER_SANITIZE_STRING);
$user_cupfi=filter_var($_POST["userCupfi"], FILTER_SANITIZE_STRING);
$user_cupfr=filter_var($_POST["userCupfr"], FILTER_SANITIZE_STRING);
your replies will be highly appreciated
Just because you name a variable user_* doesn't mean that is what the name of the field is in the serialized POST data. You would still be looking for $_POST['fl'], $_POST['fi'] etc.
I don't understand why you think you need to serialize sets of input groups individually. You should just serialize the whole form at once.
I also see no reason why you need to have all this logic around unique id's with the counter and what not. If you are not using id's at all, just drop them altogether.
You might also consider simply using clone techniques to generate your dynamically added fields. You could greatly simplify all that javascript code by doing these things.
A more reasonable implementation may look like this.
HTML (cleaning up your code - consistent use of double quotes around properties, better strategy for class and id usage, etc.)
<div id="batch">
<div class="batchDiv">
<h4 class="batchLabel">Batch #1 :</h4>
<label>Flavor</label>
<input class="textbox" type="text" name="fl[]" value=""/>
</br>
<label>Filling</label>
<input class="textbox" type="text" name="fi[]" value="" />
</br>
<label>Frosting</label>
<input class="textbox" type="text" name="fr[]" value=""/>
</br>
</div>
</div>
Javascript:
$(document).ready(function() {
$('#Add').click(function(){
var $existingBatches = $('.batchDiv');
var count = $existingBatches.size();
if (count < 5) {
// get last batch div
var $newBatch = $existingBatches.last().clone();
// reset input values to empty string
$newBatch.find('input').val('');
// change batch label
count++;
$newBatch.find('.batchLabel').html('Batch #' + count + ' :');
// append to document
$newBatch.appendTo('#batch');
} else {
// alert or whatever
}
});
$('#Remove').click(function(){
var $existingBatches = $('.batchDiv');
var count = $existingBatches.size();
// delete last batch item if more than 1 exists
if(count > 1) {
$existingBatches.last().remove();
} else {
// alert or whatever
}
});
});
Now you haven't shown your AJAX code, but all you would need to do is something like:
var url = '/some/url';
var postData = $('[some form selector]').serialize();
var dataType = '...'; //whatever dataType you are expecting back
$.post(url, postData, function(){
// success handler
}, dataType));
Your data when then be available in PHP script at $_POST['fl'], etc.
I have Jquery code that can create multiple text boxes .Now, i want to submit my text boxes' values so that i could get them using PHP on next page.I want to submit text box in the same way as ( )
and on the second page,i could get values using POST method.How can i i post multiple text values in this case and how can i retrieve them on the next page using php?? Plz help as i am a new bee.
CODE:
<head>
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--; $("#TextBoxDiv" + counter).remove(); });
$("#getButtonValue").click(function ()
{
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
</head><body>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='textbox' id='textbox1' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
</body>
Try to giving name for text boxes as array
e.g. input type='textbox' name='textbox[]' id='textbox1'
and access it on PHP page as array
$arrayRequest = $_REQUEST['textbox'];
I wrote script directly in html file, it adds some pagination feature, and it works just fine until it's in HTML file, but I just cant get how to transfer this script to external js file and make it run from there. So heres html part :
<form id="moredisplay" method="get" style="display:inline;">
<input class="hiddeninteger" type="hidden" name="loadmore" value="">
<!--LIMIT CHANGER-->
<input type="checkbox" title="" id="limitcheck" name="limit" value="<?php echo $vsego;?>" style="display:none;">
<input type="checkbox" title="" id="skipforfcheck" name="skip_items" value="" style="display:none;">
<input type="checkbox" title="" id="skipbackcheck" name="skip_items" value="" style="display:none;">
<button type="submit" title="back" value="" id="rerurn_more_items"/>back</button>
<button type="submit" title="next" value="" id="skip_more_items"/>fowards</button>
<button type="submit" title="more content" value="<?php echo $vsego;?>" id="limit" name="limit" onclick=""/>more content</button>
<script>
var currentval = jQuery('.scippeditems').attr('value');
jQuery('#skip_items,#rerurn_items').attr('value',currentval);
var valuenumber = jQuery('#skip_items').val();
if (valuenumber == 0){
jQuery('#rerurn_items').attr('disabled', 'disabled').css({'opacity':'0.6'});
}
var itemsshow = jQuery('#limit').val();
var pagescount = (jQuery('#skip_items').attr('value'))/(jQuery('#limit').attr('value'));
if(pagescount >=5){jQuery('#skip_items, #limit').attr('disabled', 'disabled').css({'opacity':'0.6'});}//COUNT PAGES AND LOCK NEXT
function changepageforf(){
var elem = document.getElementById("skip_items");
var currentval = elem.value;
elem.value = parseInt(currentval) + 24;}//parseInt(itemsshow);}
function changepageback(){
var elem = document.getElementById("rerurn_items");
var currentval = elem.value;
elem.value = parseInt(currentval) - 24;}//parseInt(itemsshow);}
</script>
<script>
jQuery(document).ready(function(){
jQuery('#limit').click(changelimit);//RUN FUNCTION ON LIMIT CHANGE
if ( document.location.href.indexOf('&limit') > -1 ) {//IF URL CONTAINS LINES LIMIT
jQuery('#rerurn_items, #skip_items').hide()//HIDE PAGINATION
jQuery('#rerurn_more_items, #skip_more_items').show()//SHOW LIMIT PAGINATION
var checkval = jQuery('#limitcheck').attr('value');
var currentvalskip = jQuery('.scippeditems').attr('value');
jQuery('#skipforfcheck').attr('value', (parseInt(checkval)+parseInt(currentvalskip)));//NEXT BTN VALUE
var currentforfaction = jQuery('#skipforfcheck').attr('value')
jQuery('#skipbackcheck').attr('value',Math.ceil( ( (parseInt(currentforfaction)-parseInt(checkval) ) - parseInt(checkval) ) ) );//PREV BTN VALUE
var pagescount = (jQuery('#skipforfcheck').attr('value'))/(jQuery('#limitcheck').attr('value'));
if(pagescount >=5){jQuery('#skip_more_items, #limit').attr('disabled', 'disabled').css({'opacity':'0.6'});}//COUNT PAGES AND LOCK NEXT
if( jQuery('#skipbackcheck').attr('value') <= 0 ){ jQuery('#skipbackcheck').attr('value', 0 );}//RETURN 0 AS A VALUE IF NEGATIVE
jQuery('#skip_more_items').click(function(){//SUBMIT NEXT BTN
jQuery('#limitcheck').attr('checked', true);
jQuery('#skipforfcheck').attr('checked', true);
jQuery('#moredisplay').submit()
});
jQuery('#rerurn_more_items').click(function(){//SUBMIT PREV BTN
jQuery('#limitcheck').attr('checked', true);
jQuery('#skipbackcheck').attr('checked', true);
jQuery('#moredisplay').submit()
});
}
function changelimit(){//LIMIT INCREASE STEP
var elem = document.getElementById("limit");
var currentval = elem.value;
elem.value = parseInt(currentval) + 6;}//HOW MUCH
var valuenumber = jQuery('#skip_items').val();
if (valuenumber == 0){//HIDE PREV BTN IF NO PREV
jQuery('#rerurn_more_items').attr('disabled', 'disabled').css({'opacity':'0.6'});
}
});
</script>
</form>
What i did try: copied script and put in in the pagination.js file and called a script on the top of the page like this
$document =& JFactory::getDocument();
$document->addScript("jquery/pagination.js");
but that doesnt work...Im new to jQuery so please dont bash me if im just stupid:L)
You need to wrap your code in:
$(document).ready( function() {
// your code here
});
As Aspiring Aqib pointed out, you need to start your JQuery script with either
$(document).ready( function() {
// your code here
});
or
$(function() {
// your code here
});
This is basically saying, ' wait until the DOM has been fully created before executing the script inside that function.
Both Aspiring Aqib and Dave were right about wrapping your jQuery code in the $(function(){//code goes here}); block.
Yet one more common mistake is not loading jQuery library file and your own .js files in the correct order, which might be tricky to find out as there is no warning anywhere in your editor or browser. The jQuery library must precede all your own .js files.
I have a form post.php where the user inputs data and receivepost.php where the data entered is transferred through Ajax post. I want to achieve the following in the receivepost.php:
if (button save is pressed) {
save to database
} else if (button retrieve is pressed) {
retrieve from database
}
I tried using isset($_POST['submit']) on the reveivepost.php but it does not detect the button which is pressed. The Ajax post is working and all the data is available on the receivepost page. I have another solution that is to create 2 different PHP files and run them according to the button pressed but I think there is a better solution to it.
Here is my ajax call :
$("document").ready(function () {
$("#submit").click(function () {
var xmlhttp;
// test browsers
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// get the values of textboxes
var desc_text = $("#desc").val();
var speed_text = $("#speed").val();
var tarea_text = $("#tarea").val();
// variable to hold value of textboxes
var content = "desc=" + desc_text + "&speed=" + speed_text + "&tarea=" + tarea_text;
// open the request
xmlhttp.open("POST", "receivepost.php", true);
// set header
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// check xmlhttp state and status and display text in div
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('para').innerHTML = xmlhttp.responseText;
}
}
// send the content of the textboxes
xmlhttp.send(content);
});
});
Here is my post.php form:
<form id="myform">
<label for="description">Description:</label>
<input type="text" id="desc" name="desc" /><br/>
<label for="speed">Speed: </label>
<input type="text" id="speed" name="speed" /><br/>
<textarea id="tarea" cols="10" rows="10" name="tarea"></textarea><br/>
<input type="button" id="submit" name = "submit" value="Save">
<input type="button" id="retrieve" name="retrieve" value="Retrieve">
</form>
<div id="para"></div>
Try to add to the content an extra parameter called button-pressed which you can later use in receivepost.php as below:
if($_POST['button-pressed']=="save"){
//savetodb code
}
else if($_POST['button-pressed']=="retrieve"){
//retreivefromdb code
}
Perhaps you have two JavaScript functions, one on each button:
$("#submit").click(function () {
var content = "button-pressed=save" + "&desc=" + desc_text + "&speed=" + speed_text + "&tarea=" + tarea_text;
$("#retrieve").click(function () {
var content = "button-pressed=retrieve" + "&desc=" + desc_text + "&speed=" + speed_text + "&tarea=" + tarea_text;
Hope this helps?
<input type="button" id="submit" name ="submit" value="save" onClick="fnc(this.id)">
<input type="button" id="retrieve" name="retrieve" value="retrieve" onClick="fnc(this.id)">
<script type="text/javascript">
function fnc(myid) {
var val=document.getElementById(myid).value;
alert(val);
}
</script>