how to get two dynamic textbox value in jquery - javascript

Thanks in advance, Actually i have a form with two hidden textbox fields one is <input type="hidden" name="item_name" class="course_name" value="<?php echo $cartData['exam'];?>"> and the other is <input type="hidden" name="amount" class="amount" value="<?php echo $priceTotal;?>">, the the value is taken inside the hidden field dynamically from PHP code through loop. So how can i get the dynamic values of "item_name" textbox field and "amount" textbox field in comma seperated using Jquery when clicking the image button with id="placeOrder".
For example like this : for amount-->200,300 and for course name -->PMP,CAPM . I have written some code it will take the values within the jquery each loop but i have to pass through ajax as json format like this data : {cname:course_name,priceBox:textboxVal} so value with comma seperated value should pass through course_name & textboxVal.
My Page is
<html>
<head>
<title></title>
<script>
$(document).ready(function(){
var myArray = [];
$('.amount').each(function(){
var textboxVal = $(this).val();
//alert(textboxVal);
});
var myCourse = [];
//dynamic course name
$('.course_name').each(function(){
var course_name = $(this).val();
//alert(course_name);
});
if(textboxVal!="")
{
$.ajax({
type : "POST",
url : "/invl_exams/cart",
cache : "false",
data : {cname:course_name,priceBox:textboxVal},
success : function(result){
console.log(result);
}
});
}
});
</script>
</head>
</html>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<td>
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="shopbusiness#myshop.com">
<input type="hidden" name="upload" value="1">
<?php
if(isset($cartDatas))
{
$itm_no = 1;
$amt = 0;
foreach($cartDatas as $key=> $cartData)
{
$prices = $cartData['price'];
$prd_price = ltrim($prices,'$');
$priceTotal = number_format((float)$prd_price, 2, '.', '');
?>
<input type="hidden" name="item_number" value="<?php echo $itm_no++;?>">
<input type="hidden" name="item_name" class="course_name" value="<?php echo $cartData['exam'];?>">
<input type="hidden" name="amount" class="amount" value="<?php echo $priceTotal;?>">
<input type="hidden" name="shipping" value="shipping Address">
<input type="hidden" name="quantity" value="<?php echo $cartData['orders'];?>">
<?php
$price = ltrim($prices,'$');
$orders = $cartData['orders'];
$amt_Total = $price * $orders;
$amt += $amt_Total;
$amt_Total = number_format((float)$amt, 2, '.', '');
///$amt_Total = round($price * floatval( $orders ),2);
}
?>
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="amount" value="<?php echo $amt_Total;?>">
<?php
}
?>
<input type="image" src="http://www.paypal.com/en_US/i/btn/x-click-but03.gif" name="submit" id="placeOrder">
</td>
</form>

You can do something like following:
$(function(){
var amount = [];
var course = [];
$('.amount').each(function(){
amount.push($(this).val());
});
$('.course_name').each(function(){
course.push($(this).val());
});
console.log(amount.join(',')); //comma seperated value
console.log(course.join(',')) //comma seperated value
});
DEMO

You can use jQuery and attribute selectors to get the value:
var item_name = $('input[name=\'item_name\']').val();
var amount = $('input[name=\'amount\']').val();
var result = item_name + ',' + amount;
Now you can put this in your click handler.

If your inputs are enclosed within form element you can use this serialize the form input values to json object and then pass it to ajax call.
var postData = $("#enclosing_form_elm").serializeObject();
and in your script add reference to serialize object function after jquery
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
Just a demo https://plnkr.co/edit/7maJAUSdakDuvVqXhnzi?p=preview
Thanks to Convert form data to JavaScript object with jQuery

Related

shorter way to collect data and update a table

here is my way to submit a form.
In reality it has much more text inputs.
Everything works fine, but I hope there is a shorter way, especially on server side, regarding that data-col on client side is in fact a corresponding column name on server.
html
<form id='dform'>
<input type='text' class='dinp' data-col='nick'>
<input type='text' class='dinp' data-col='state'>
<input type='text' class='dinp' data-col='city'>
<input type='text' class='dinp' data-col='uname'>
<input type='text' class='dinp' data-col='pass'>
</form>
js
$('#msave').on('click', function(){
let id=$('.aact').attr('data-id');
let obj = {};
$('.dinp').each(function(){
let col = $(this).attr('data-col');
obj[col] = $(this).val().trim();
});
obj = JSON.stringify(obj);
$.post('a_users_pro.php', {fn: 'm_save', args: [id, obj]}, function(data){
console.log(data);
});
});
php
function m_save($id, $obj){
global $db;
$obj = json_decode($obj);
$sql = "
update users
set nick = :anick
, state = :astate
, city = :acity
, uname = :auname
, pass = :apass
where id = :aid
";
$st = $db->prepare($sql);
$st -> execute([
":aid" => $id,
":anick" => $obj->nick,
":astate" => $obj->state,
":acity" => $obj->city,
":auname" => $obj->uname,
":apass" => $obj->pass
]);
}
You can use the name attribute of input elements with your data-col value and pass the serialized form data to the AJAX request. Here is a implementation:
HTML:
<form id="myForm">
<input type="text" name="name" placeholder="name">
<input type="email" name="email" placeholder="email">
<input type="number" name="age" placeholder="age">
<input type="hidden" name="id" value="1">
<button type="submit">Submit</button>
</form>
JavaScript:
$(document).ready(function() {
$('#myForm').on('submit', function(e) {
e.preventDefault();
$.post('update.php', $('#myForm').serialize());
});
});
PHP:
<?php
if (isset($_POST)) {
// Validate request
$sql = 'UPDATE users
SET
name = :name,
email = :email,
age = :age
WHERE id = :id
';
$st = $db->prepare($sql);
$st->execute([
':id' => $_POST['id'],
':name' => $_POST['name'],
':email' => $_POST['email'],
':age' => $_POST['age'],
]);
}
?>
In your example I can't see where .aact and data-id come from. I assumed that the id value would be available to the view so I passed it to the request as a hidden input.

What have i done wrong in this javascript calculation?

I have two inputs that can hold a value and where a value is typed in.
calculate() kinda do the job but I getting an error in the console :
Uncaught TypeError: Cannot set property 'value' of null(…)
But for calculate() I get only that error!
if($sal>10){
echo '<td>
<input type="text" oninput="calculate()" name="monthly_sum_019" id="monthly_sum_019" value="">
<input type="hidden" class="input toggle all" id="monthly_sum_019" oninput="calculate()" value="" placeholder="'.$sal.'"></td>';
}else{
echo '<td>
<input type="text" oninput="calculate()" name="monthly_sum_019" id="" value="">
<input type="hidden" class="input toggle all" id="monthly_sum_019" oninput="calculatez()" value="'.$sal.'"></td>';
}
And have 2 inputs that returns result of calculation:
if($sal>10){
echo '<td>
<input type="text" id="result" name="reward_019" value=""></td>';
}else{
echo '<td>
<input type="text" id="result2" name="reward_019" value=""></td>';
}
And the javascript:
<script>
function calculate() {
var myBox1 = parseFloat(document.getElementById('monthly_sum_019').value);
var myBox2 = parseFloat(document.getElementById('norm').value);
var myBox3 = parseFloat(document.getElementById('time_hours_019').value);
var result = document.getElementById('result');
var myResult = (myBox1 / myBox2) * myBox3;
result.value = myResult.toFixed(2);
}
</script>
<script>
function calculatez() {
var myBox1 = parseFloat(document.getElementById('hourmoney').value);
var myBox3 = parseFloat(document.getElementById('time_hours_019').value);
var result2 = document.getElementById('result2');
var myResult = myBox3 * myBox1;
result2.value = myResult.toFixed(2);
}
</script>
What is wrong?
Usually Cant do something of NULL means you try to select element but it's not presented in DOM.
I see that you try to select element with ID result2 but in your provided code I see that when $sal > 10 == true you do not put element with such ID.
Since it's PHP code you can have same ID in both if and else parts (but not in same part multiple times).

Creating multidimensional array from dynamic form in JQuery

I'm trying to capture values from inputs and put them in JQuery object instead of having to deal with PHP indexing.
This is the form
<form name="second_form" id="second_form" action="#" method="POST">
Add Champion
<div id="ChampionInput">
</div>
<br><br>
<input id="obj" type="hidden" name="obj">
<input type="submit" name="submit">
</form>
My script that I'm trying to use to recreate the array:
$("#second_form").submit(function(event) {
var object = [];
$('.Champion').each(function() {
var champion = {
'name': $(this).find(".ChampionInput").val(),
'change': $(this).find("input:radio:checked").val(),
'General_Description': [],
'General_Change':[]
};
$(this).find('.GeneralChange').each(function() { champion.General_Description.push($(this).children(".GeneralChangeDescription").val());
champion.General_Change.push($(this).children(".General_Change").val());
});
object.push(champion);
});
object = JSON.stringify(object);
$('#obj').val(object); //Sending object to hidden input
});
And here is the way I used to create this PHP array which messes up indexing when I delete some inputs when creating the form
foreach($_POST['champion'] as $champion){
if(isset($_POST['Release'][$ChampionNumber])){
$_POST['Release'][$ChampionNumber]=='New' ? $champions[$champion]['New']=1 : $champions[$champion]['New']=0;
$_POST['Release'][$ChampionNumber]=='Rework' ? $champions[$champion]['Rework']=1 : $champions[$champion]['Rework']=0;
}
if(!empty($_POST['GeneralChangeDescription'][$ChampionNumber])){
foreach($_POST['GeneralChangeDescription'][$ChampionNumber] as $indexGeneral=>$GeneralChangeDescription){
$GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] =ucfirst(trim($GeneralChangeDescription));
if(substr($GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1], -1)!='.'){
$GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1].'.';
}
$GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = preg_replace('/\s\/\s/','/',$GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1]);
$GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = preg_replace( '/(\.?\d\/?%?)+/', '<strong>$0</strong>', $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1]);
$GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = preg_replace( '/\b\w+\.(jpg|png|gif)/', '', $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1]);
$champions[$champion]['General']['Change'][] = $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1];
$champions[$champion]['General']['Type'][] = $_POST['GeneralChange'][$ChampionNumber][$indexGeneral];
}
}
$ChampionNumber++;
}
Removing champions
$('div#ChampionInput').on('click', 'a.Remove',function(){
var champion = $(this).closest('.Champion');
var id = champion.data("id");
var nextChampion = champion;
while((nextChampion = nextChampion.next()).length != 0){
nextChampion.attr("data-id",id++);
nextChampion.children('.ChampionInput').attr('placeholder','Champion '+ id);
}
championNumber=id+1;
championNumberArray=id;
champion.remove();
});
Removing changes
$('div#ChampionInput').on('click', 'a.RemoveGeneralChange',function(){
$(this).closest('.GeneralChange').remove();
});
Here is how my array looks like in PHP: http://i.imgur.com/rURnNTG.png and I want to get array looking like that after sending JQuery object through hidden input in form and obtaining it in PHP. Here is how my JQuery object looks like right now http://imgur.com/2r9iyKN which is not even close.
Here is also JSfiddle of form creation: jsfiddle.net/g50zd384/
If you really need that array, so create it in PHP after sending the form:
$array;
for($i = 1; $i <= count($_POST['champion']); $i++) {
$champion = $_POST['champion'][$i];
$array[$champion]['General'] = $_POST['GeneralChangeDescription'][$i];
$array[$champion]['Type'] = $_POST['GeneralChange'][$i];
$array[$champion]['Release'] = $_POST['Release'][$i];
}
Your form should be created with this names:
championNumber = 1;
championNumberArray = 0;
$('a#AddChampion').on('click',function(){
$('div#ChampionInput').append(
'<div class="Champion">\
<br>\
<input type="text" class="ChampionInput" name="champion['+championNumber+']" placeholder="Champion '+championNumber+'">\
<datalist id="champions"></datalist>\
<input type="radio" name="Release['+championNumber+']" value="New">New\
<input type="radio" name="Release['+championNumber+']" value="Rework">Rework\
<input type="radio" name="Release['+championNumber+']" value="None" checked>None\
Add General Change\
<div class="GeneralChanges">\
</div>\
<br>\
<div>');
championNumber++;
});
$('div#ChampionInput').on('click','a.AddGeneralChange', function(){
var id = $(this).data('id');
$(this).siblings('.GeneralChanges').append(
'<div class="GeneralChange">\
<textarea type="text" size="20" rows="3" cols="50" maxlength="500" class="GeneralChangeDescription" name="GeneralChangeDescription['+id+'][]" placeholder="Enter General Change Description"></textarea>\
<select class="General_Change" name="GeneralChange['+id+'][]">\
<option value="buff">Buff</option>\
<option value="nerf">Nerf</option>\
<option value="new">New</option>\
<option value="change">Change</option>\
<option value="bugfix">Bugfix</option>\
</select>\
</div>');
});
It is important, that you name your inputs in this way!
..not the best way, but better than sending json data in a hidden input form. I hope this could help you.

Posting JavaScript Variable to MySQL using PHP

I am trying to send a JavaScript variable to PHP but not exactly sure how to do it, a few things have said Ajax but I've never used it before and can't get my head around it. Does anyone know what the easiest way to do this would be? The column which I am attempting to populate in my DB is called 'cogs'.
I have the following JavaScript code:
<script>
$(document).ready(function() {
$('#duration-select').change(function() {
var cogs = $('#cogsday').html();
cogs = cogs.replace(/\D/g,'');
var x =$('#duration-select').val();
var y = cogs * x;
$('#request').removeClass('hidden');
$('#duration-value').text('Total cost for this duration = ' + (y) + ' cogs');
if($(this).val() !== '') {
} else {
$('#duration-value').text('');
}
});
$('#request').click(function() {
var cogs = $('#cogsday').html();
cogs = cogs.replace(/\D/g,'');
var x =$('#duration-select').val();
var y = cogs * x;
$('#total').text(y);
});
});
</script>
And the following HTML code:
<label id="total"></label>
Here is where I am trying to post the data, everything else is posting except for the $cost:
<form name="form" method="post">
<div class="modal-footer">
<?php
if ($row3['availability'] === 'Available') {
if (isset($_POST['request'])) {
$to_id = $row3['customerid'];
$from_id = $_SESSION['customerid'];
$time_sent = date('Y-m-d H:i:s');
$subject = 'Request for ' . $row3['title'];
$title = $row3['title'];
$listingid = $listingid;
$cost = $_POST['total']; //posting 0
$message = $customer_data['first_name'] . ' ' . $customer_data['last_name']
$request = mysql_query("INSERT INTO messages (to_id, from_id, listing_id, time_sent, subject, message, cogs, messagenumber, title, msgrand) VALUES ('$to_id', '$from_id', '$listingid', '$time_sent', '$subject', '$message', '$cost', '1', '$title', '$randomString')") or die(mysql_error());
}
}
?>
<input type="submit" class="btn btn-success" name="request" value="Yes" />
<input type="submit" class="btn btn-danger" data-dismiss="modal" value="No" />
</div>
</form>
Then I am trying to post the value of the label id=total to my db or the JavaScript variable (y). The problem is that 0 is always being sent to the DB when it should instead be the value that is in the label where the id is total.
Use name parameter for hidden variable and it will be automatically passed to PHP .
<label id="total"></label>
<input type="hidden" name="total" id="nameID"/>
in javascript below $('#total').text(y); write $('#nameID').val(y); . Everything will work properly.
You used total label , but $_POST recognizes only input type so use input type=.... instead of a label,divs etc.
IF YOU REAllY NEED ANSWER REPLY HERE
you have make an input type and its value is to be set by that javascript and then you'll be able to get that $cost value in php code
<input type="hidden" value="" name="total" id="total">
..................
$("#total").val(y);
You can use this to send the variables....
<input type="text" id="name" class="name" placevalue="Enter you name" required /><br><br>
<input type="text" id="email" class="email" placevalue="Enter you name" required /><br><br>
<button id= "det_submit" onclick="submit_det()"> Submit </button>
<script>
function submit_det() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if(name != "" && email != "") {
$.post(
'xx.php',
{
name : document.getElementById("name").value,
email1 : document.getElementById("email").value,
},
function(data){
alert(data);
});
} else {
alert("empty");
}
}
</script>
here is xx.php
<?php
if(isset($_POST['name']) && isset($_POST['email1'])) {
$name = $_POST['name'];
$email = $_POST['email1'];
//code to insert into your database......
}
?>
Use a ID and Name for hidden parameter like this
<label id="total"></label
<input type="hidden" name="name" id="name"/>
and in jQuery edit the code like this
$('#total').text(y);
$('#nameID').val(y);
hope that it will work

how to fetch values from array input in javascript

How do I properly fetch values from array in javascript:
<html>
<head>
<script type="text/javascript">
function proc()
{
var cost = document.yoh.coz.value;
var qtybuy = document.yoh.qbuys.value;
var st = cost * qtybuy;
var tbox = document.yoh.subtotal;
if (tbox)
{
tbox.value = st;
}
}
</script>
</head>
<body>
<?php
include('conn.php');
$prodname = $_GET['prodname'];
$result = query_database("SELECT * FROM prod_table WHERE PRODUCT='$prodname'", "onstor", $link);
?>
<?php while ( $row = mysql_fetch_array($result) ) { ?>
<form name="yoh" method="get">
Product id: <input type="text" name="prodid" value=""><br/>
Cost: <input type="text" name="coz" value="<?php echo $row['S_PRICE']; ?>"><br/>
Quantity to buy:<input type="text" name="qbuys" value="" onkeyup="proc();"></br>
Subtotal:<input type="text" name="subtotal" value=""></br>
</form>
</body>
<?php } ?>
</html>
As you can see this program will just multiply the 2 values. One of the values would be fetched from the database, and the other comes from the user.
If I do it this way, I don't get any results:
<html>
<head>
<script type="text/javascript">
function proc()
{
var cost = document.yoh.coz[].value;
var qtybuy = document.yoh.qbuys[].value;
var st = cost * qtybuy;
var tbox = document.yoh.subtotal[];
if (tbox)
{
tbox.value = st;
}
}
</script>
</head>
<body>
<?php
include('conn.php');
$prodname = $_GET['prodname'];
$result = query_database("SELECT * FROM prod_table WHERE PRODUCT='$prodname'", "onstor", $link);
?>
<?php while ( $row = mysql_fetch_array($result) ) { ?>
<form name="yoh" method="get">
Product id: <input type="text" name="prodid[]" value=""><br/>
Cost: <input type="text" name="coz[]" value="<?php echo $row['S_PRICE']; ?>"><br/>
Quantity to buy:<input type="text" name="qbuys[]" value="" onkeyup="proc();"></br>
Subtotal:<input type="text" name="subtotal[]" value=""></br>
</form>
</body>
<?php } ?>
</html>
Do I need to include the index manually? What do I need to do to achieve the same results when using arrays.
You can use a name value:
cost=document.yoh.elements['coz[]'].value;
You need to iterate through the arrays. To iterate through an array (or object) in JavaScript:
for (key in arr){
// The key will be set to each key in the array (arr)
// The value at that key will be arr[key] (like always)
}
I'm not entirely sure what your goal is, but in general, know that the "[]" syntax is PHP only, JavaScript treats it as any other name (and possibly as a syntax error).

Categories

Resources