My variables aren't passing to the function - javascript

UPDATE: Ali helped me get the values populating, but the issue now is that it's pulling the data from the last game option in the array every time. I need to click the game and show the info for that game. I've updated my code below.
ORIGINAL: I'm trying to fix a page that contains a form to search for nearby games and display the results. Once the results are displayed, I need to be able to click the results to show information for each of the games in a pop up window.
It is currently using the default values of the form to populate the popups, eg every club will show 6.15 as the time until I change the time of the search form, in which case they will all show that time as the time of the game within the pop up.
This is the code used to display the games:
<div class="game-search-result-outer pop-profile-view pop-profile-view1">
<ul>
<?php $src_game = '';
if(!empty($game_lists)){
foreach($game_lists as $glist){
if($glist->count_golfer_join < $glist->golfer){
?>
<li class="game<?=$glist->id?>" onclick="getGameValue('<?=$glist->id?>','<?=$glist->club_name?>','<?=$src_game?>','<?=$glist->handicap_min?>','<?=$glist->handicap_max?>','<?= date("d/m/Y",strtotime($glist->start_date))?>');">
<a href="#" data-id="<?=$glist->id?>">
<div class="club-img">
<img src="<?=$src_game?>">
</div>
<h3><?=$glist->club_name?> <br> <?= date("d/m/Y",strtotime($glist->start_date))?> at <?= date("G:i a",strtotime($glist->start_time))?> <br> Handicap between <?=$glist->handicap_min?> and <?=$glist->handicap_max?></h3>
</a>
<input type="hidden" name="start_date<?=$glist->id?>" id="start_date<?=$glist->id?>" value="<?= date("d/m/Y",strtotime($glist->start_date))?>">
</li>
<?php }
} }else{ echo "No Games Available, please refine your search" ;} ?>
</ul>
</div>
Onclick, it activates this function:
<script>
function getGameValue(game_id,club_name,src,handicap_min,handicap_max) {
var golf_handicap = '<?=$USERDETAILS->golf_handicap?>';
var start_date = $("#start_date"+game_id).val();
//var start_date = '<?= date("d/m/Y",strtotime($glist->start_date))?>';
var play_against = $("#play_against option:selected").text();
var start_time = '<?= date("G:i a",strtotime($glist->start_time))?>';
var handicap1 = $("#handicap1").val();
var gofer = $("input[name='golfer']:checked").val();
var handicapRange1 = handicap_min;
var handicapRange2 = handicap_max;
var p = $('.game'+game_id+' > h3');
if(golf_handicap<handicapRange1 || golf_handicap>handicapRange2){
alert("Unfortunately you cannot join this game, your handicap "+golf_handicap+" is not within the handicap range.");
document.location.reload();
return false
}
var data ='<div class="result-pop-box-img"><img src="'+src+'"></div><div class="result-pop-box-text"><h3>'+club_name+'</h3><p class="game<?=$glist->id?>">Hi <?=$USERDETAILS->first_name?>, you\’re about to join a game at '+club_name+' on '+ start_date +' at '+ start_time +' for '+ gofer +' golfers playing against '+ play_against +' with a handicap between '+ handicap1 +'. If this is correct, click the “Confirm” button. If you want to edit your booking, click cancel</p></div>';
$("#getGameValueID").html(data);
}
</script>
Thank you for any help.
UPDATE
Here is the code for the form:
<form>
<div class="form-control">
<label>Location
<?php $zip = ($USERDETAILS->s_address)?', '.$USERDETAILS->zip:''.$USERDETAILS->zip;
$location = $USERDETAILS->s_address.$zip; ?>
<span class="loc-icon"><input type="text" name="location" class="icon-input" id="location" value="<?=$location?>"></span>
</label>
</div>
<div class="form-control">
<label>Date
<span class="cal-icon">
<div>
<!--<input type="text" id="datepicker" name="start_date">-->
<input type="date" id="start_date2" name="start_date2" value="<?php if($_GET['start_date2']){echo $_GET['start_date2'];}else { echo date("Y-m-d",strtotime('+1 day', time()));} ?>" min="<?=date("Y-m-d",strtotime('+1 day', time()))?>" max="<?=date("Y-m-d",strtotime('+1 year', time()))?>">
</div>
</span>
<!--<input type="text" name="date" class="icon-input"></span>-->
</label>
</div>
<div class="golfer-select">
<div class="form-control">
<label>Golfers</label>
<?php if($_GET['golfer']==1) $gcheck = 'checked';
elseif($_GET['golfer']==2) $gcheck2 = 'checked';
elseif($_GET['golfer']==3) $gcheck3 = 'checked';
?>
<div class="x3">
<label>
<input type="radio" name="golfer" value="1" <?=$gcheck?>>
<span>1</span>
</label>
</div>
<div class="x3">
<label>
<input type="radio" name="golfer" value="2" <?=$gcheck2?>>
<span>2</span>
</label>
</div>
<div class="x3">
<label>
<input type="radio" name="golfer" value="3" <?=$gcheck3?>>
<span>3</span>
</label>
</div>
</div>
</div>
<div class="form-control">
<label>Play Againts</label>
<select name="play_against" id="play_against">
<?php foreach($categories as $cate){
if($_GET['play_against']==$cate->id) {
$csel = 'selected';
}else{ $csel = ''; }
?>
<option value="<?=$cate->id?>"<?=$csel?>><?=$cate->name?></option>
<?php } ?>
</select>
</div>
<div class="form-control">
<div class="time-range">
<label>Start Time</label>
<div class="range range-step range-step-popup">
<input value="1" type="range" max="60" min="0" step="1" list="ticks2" onclick="getTimeValue();">
<datalist id="ticks2">
<?php $minute=00; $counter=0;
for($start_time=06;$start_time<21;){
if($minute>45){
$minute = 00;
$start_time++;
}?>
<option value="<?=$counter?>"><?=$start_time?>.<?=$minute?></option>
<?php
$counter++;
$minute= $minute+15;
}?>
</datalist>
<output id="get_range" class="__range-output-square"></output>
</div>
<input type="text" name="start_time" id="start_time">
<script>
function getTimeValue() {
var range_val = document.getElementById('get_range').innerHTML;
document.getElementById('start_time').value=range_val;
}
</script>
</div>
</div>
<div class="form-control">
<div class="dis-range">
<label>Distance (in miles)</label>
<div class="range range-step range-step-popup">
<?php $dist_val = array(0,5,10,15,20,25,30,35,40,50,60,75,100,125,150,200,300,500,1000,2000,3000,5000,10000);
if(in_array($_GET['distance'],$dist_val)){
$key_val = array_search ($_GET['distance'], $dist_val);
$sel_dist_key = $key_val;
}else{
$sel_dist_key = 15;
} ?>
<input value="<?=$sel_dist_key?>" type="range" max="22" min="0" step="1" list="ticks3" onclick="getValue();">
<datalist id="ticks3">
<option value="0">0</option>
<option value="1">5</option>
<option value="2">10</option>
<option value="3">15</option>
<option value="4">20</option>
<option value="5">25</option>
<option value="6">30</option>
<option value="7">35</option>
<option value="8">40</option>
<option value="9">50</option>
<option value="10">60</option>
<option value="11">75</option>
<option value="12">100</option>
<option value="13">125</option>
<option value="14">150</option>
<option value="15">200</option>
<option value="16">300</option>
<option value="17">500</option>
<option value="18">1000</option>
<option value="19">2000</option>
<option value="20">3000</option>
<option value="21">5000</option>
<option value="22">10000</option>
</datalist>
<output id="get_distance" class="__range-output-square"></output>
</div>
<input type="hidden" name="distance" id="distance" value="">
<script>
function getValue() {
var range_val = document.getElementById('get_distance').innerHTML;
document.getElementById('distance').value=range_val;
}
</script>
</div>
</div>
<div class="form-control">
<div class="handi-range">
<label>Handicap</label>
<section class="range-slider range range-step range-step-popup">
<span class="rangeValues"></span>
<input value="0" min="0" max="54" step="1" type="range">
<input value="54" min="1" max="54" step="1" type="range">
<datalist class="in-dots" id="">
<?php for ($handcap=0;$handcap<=54;$handcap++){
echo '<option value="'.$handcap.'">'.$handcap.'</option>';
} ?>
</datalist>
</section>
<input type="hidden" name="handicap" id="handicap1">
</div>
</div>
<div class="sp20"></div>
<input type="submit" name="search" value="Search" class="green-btn-arrow" onclick="getInfo();">
<!--<button class="green-btn-arrow">Search</button>-->
</form>

Add a class attribute to each li;
<?php
...
<!-- add class to li based on glist_id so you can access to each element in the getGameValue function-->
<li class="game<?=$glist->id?>" onclick="getGameValue('<?=$glist->id?>','<?=$glist->club_name?>','<?=$src_game?>','<?=$glist->handicap_min?>','<?=$glist->handicap_max?>','<?= date("d/m/Y",strtotime($glist->start_date))?>', '<?= date("G:i a",strtotime($glist->start_time))?>');">
Now in your function
function getGameValue(game_id,club_name,src,handicap_min,handicap_max, start_date, start_time) {
// remove these lines and add them to inputs
// var start_date = '<?= date("d/m/Y",strtotime($glist->start_date))?>';
// var start_time = '<?= date("G:i a",strtotime($glist->start_time))?>';
// get h3 element
var h3 = $('.game'+game_id+' > h3');
// change the h3 innetHtml like here
}
other than this you can do whatever you want with that information inside the getGameValue function.

Related

Unable to repopulate form

I have created the below mentioned form in Codeigniter, where there is 4 level dependent drop down list. Everything work as expected while I am in the first form. When I press the add button so that there is a regenerated form just like the first one, whenever I select the country field and expect based on my selection to have the relevant options in the second drop down menu (championship) it doesn't work. No data is coming based on my country selection. It looks like there is no call to the JavaScript.
Could you please help me to understand where is my mistake after pressing the add button, so that no matter how many forms I create, I will have relevant calls to the functions in my controller where it brings the relevant data to the depentened drop down menus?
Thank you very much!
<div class="container box">
<br />
<br />
<h3 align="center">Available Championships</h3>
<br />
<?php echo form_open_multipart('dynamic_dependent'); ?>
<div id="dynamic_field">
<div class="form-group">
<select name="country[]" id="country" class="form-control input-lg">
<option value="">Select Country</option>
<?php
foreach($country as $row)
{
echo '<option value="'.$row->id.'">'.$row->name.'</option>';
}
?>
</select>
</div>
<br />
<div class="form-group">
<select name="championship[]" id="championship" class="form-control input-lg">
<option value="">Select Championship</option>
</select>
</div>
<br />
<div class="form-group">
<select name="home_team[]" id="home_team" class="form-control input-lg">
<option value="">Select Home Team</option>
</select>
</div>
<div class="form-group">
<select name="away_team[]" id="away_team" class="form-control input-lg">
<option value="">Select Away Team</option>
</select>
</div>
<div class="form-group">
<input type="text" name="prediction[]" id="prediction">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" name="add" id="add" class="btn btn-success">Add More</button>
</div>
</div>
<div class="form-group">
<button>Submit</button>
</div>
<?php echo form_close(); ?>
</div>
<script type="text/javascript">
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<div id="row'+i+'"><div class="form-group"><select name="country[]" id="country" class="form-control input-lg"><option value="">Select Country</option><?php foreach($country as $row) { echo '<option value="'.$row->id.'">'.$row->name.'</option>'; } ?></select></div><div class="form-group"><select name="championship[]" id="championship" class="form-control input-lg"><option value="">Select Championship</option></select></div><div class="form-group"><select name="home_team[]" id="home_team" class="form-control input-lg"><option value="">Select Home Team</option></select></div><div class="form-group"><select name="away_team[]" id="away_team" class="form-control input-lg"><option value="">Select Away Team</option></select></div><div class="form-group"><input type="text" name="prediction[]" id="prediction"></div><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></div></div></div>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
var res = confirm('Are You Sure You Want To Delete This?');
if(res==true){
$('#row'+button_id+'').remove();
$('#'+button_id+'').remove();
}
});
});
$('#country').change(function(){
var country_id = $('#country').val();
if(country_id != '')
{
$.ajax({
url:"<?php echo base_url(); ?>index.php/dynamic_dependent/fetch_state",
method:"POST",
data:{country_id:country_id},
success:function(data)
{
$('#championship').html(data);
$('#home_team').html('<option value="">Select Home Team</option>');
$('#away_team').html('<option value="">Select Away Team</option>');
}
});
}
else
{
$('#championship').html('<option value="">Select Championship</option>');
$('#home_team').html('<option value="">Select Home Team</option>');
$('#away_team').html('<option value="">Select Away Team</option>');
}
});
$('#championship').change(function(){
var championship_id = $('#championship').val();
if(championship_id != '')
{
$.ajax({
url:"<?php echo base_url(); ?>index.php/dynamic_dependent/fetch_city",
method:"POST",
data:{championship_id:championship_id},
success:function(data)
{
$('#home_team').html(data);
$('#away_team').html(data);
}
});
}
else
{
$('#home_team').html('<option value="">Select Home Team</option>');
$('#away_team').html('<option value="">Select Away Team</option>');
}
});
</script>

How to use ajax to populate input with select option with data from database?

The question I've got in my test goes like so.
You have 1 select with 2 options(item number1 and item number2) and 2 input fields(price,weight). How would you make the input fields change without writing in them?
So after a long time of searching and trying stuff out (without much luck) I've learned that I need to use ajax for this to work. so I have tried a bunch and this is the code I've tried edit so it would work.
getAllproduct is just a select that fetches all the data inside my table with products. this is id, name, item_number, price, weight. anyhow here is my code
<?php
$sth = $db->prepare("SELECT `price`,`weight` FROM product");
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
$row = array();
json_encode($row);
?>
product.php
<div class="form-group col-2">
<label for="product">Item number</label>
<?=#$error['product']?>
<select class="form-control" name="product" id="product" onChange="getproduct(this.value)">
<?php foreach ($csv->getAllproduct() as $csv) { ?>
<option value="<?= #$csv->id ?>" selected><?= #$csv->product?></option>
<?php } ?>
</select>
</div>
<div class="form-group col-2">
<label for="weight">weight</label>
<?=#$error['weight']?>
<input type="text" name="weight" id="weight" class="form-control">
</div>
<div class="form-group col-2">
<label for="price">price</label>
<?=#$error['price']?>
<input type="text" name="price" id="price" class="form-control">
</div>
<div class="input-group">
<button type="submit" style="margin-left:15px; margin-bottom: 15px; z-index: 5" class="btn btn-success" value="Opret" name="btn_opret_maal">Submit</button>
</div>
<script>
function getproduct(val){
$.ajax({
type:"POST",
url:"pages\call.php",
data: 'product='+val,
success: function(response){
var result = JSON.parse(response);
if (result.response == true) {
var data = result.rows;
$("#weight").val(data[0].weight);
$("#price").val(data[0].price);
}else if (result.response == false) {
$('#product').append('<option>No products were found!</option>');
}
}
});
}
</script>
What I expect to be able to do is select an item number and it will automatically populate the inputfields price and weight with the data inside the database from the item number.
I haven't learned a lot of Ajax/js so Any help is appreciated.
Attempt: on other project using this code. havent gotten it to work yet.
<form class="row" method="POST" >
<div style="border-color:#dddddd;" class="dropdown-divider col-12"></div>
<script>$('#Varenummer').on('change', function() {
var selectedOption = $(this).find('option:selected');
$('#Tolminus').val(selectedOption[0].dataset.Tolminus);
$('#Tolplus').val(selectedOption[0].dataset.Tolplus);
});
</script>
<div class="form-group col-2">
<label for="Varenummer">Varenummer</label>
<?= #$error['Varenummer'] ?>
<select class="form-control" name="Varenummer" id="Varenummer">
<?php
foreach ($csv->getAllVarenummer() as $csv) {?>
<option value="<?= #$csv->id ?>" data-Tolminus="<?= #$csv->Tolminus ?>"
data-Tolplus="<?= #$csv->Tolplus ?>"><?= #$csv->Varenummer ?></option>
<?php }?>
</select>
</div>
<div class="form-group col-2">
<label for="Tolminus">Tol -</label>
<?= #$error['Tolminus'] ?>
<input type="text" name="Tolminus" id="Tolminus" class="form-control" value="">
</div>
<div class="form-group col-2">
<label for="Tolplus">Tol +</label>
<?= #$error['Tolplus'] ?>
<input type="text" name="Tolplus" id="Tolplus" class="form-control" value="">
</div>
<div class="input-group">
<button type="submit" style="margin-left:15px; margin-bottom: 15px; z-index: 5" class="btn btn-success" value="Opret" name="btn_opret_maal">Submit</button>
</div>
the jquery scrips and others are added in the footer.
As you asked above in comments: i need it to the input to change when i select an option. can i still only use php?...
Yes.
You might not need ajax at all. For your task I'd recommend to preload weight and price values into data- attributes of corresponding option elements. Then, on the select change, just get those values and paste them to inputs.
$('#product').on('change', function() {
var selectedOption = $(this).find('option:selected');
$('#weight').val(selectedOption[0].dataset.weight);
$('#price').val(selectedOption[0].dataset.price);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-2">
<label for="product">Item number</label>
<select class="form-control" name="product" id="product">
<option disabled selected>Choose product...</option>
<option value="1" data-weight="100" data-price="1000">Product 1</option>
<option value="2" data-weight="50" data-price="200">Product 2</option>
<option value="3" data-weight="25" data-price="115">Product 3</option>
</select>
</div>
<div class="form-group col-2">
<label for="weight">weight</label>
<input type="text" name="weight" id="weight" class="form-control">
</div>
<div class="form-group col-2">
<label for="price">price</label>
<input type="text" name="price" id="price" class="form-control">
</div>
<div class="input-group">
<button type="submit" style="margin-left:15px; margin-bottom: 15px; z-index: 5" class="btn btn-success" value="Opret" name="btn_opret_maal">Submit</button>
</div>
For the PHP generated select (assuming the getAllproduct method returns weight and price properties):
...
<div class="form-group col-2">
<label for="product">Item number</label>
<?=#$error['product']?>
<select class="form-control" name="product" id="product">
<?php foreach ($csv->getAllproduct() as $csv) { ?>
<option value="<?= #$csv->id ?>" data-weight="<?= #$csv->weight ?>" data-price="<?= #$csv->price ?>"><?= #$csv->product?></option>
<?php } ?>
</select>
</div>
...

Get value from drop down and return to form field

I am trying to get value from two form fields and then get their product and pass it to another form field .I am fetching data from database and then passing it dropdown.
But I am having trouble .How can you get the selected value from drop down list using JavaScript? and then pass it to other field and some operation? I have tried the following but it does not work.My piece of work is down below.Anyone who can guide me?
<form class="form-horizontal" role="form" method="post">
<div class="form-group">
Months to rent
<div class="count-input space-bottom">
<a class="incr-btn" data-action="decrease" href="#">+</a>
<input onchange="calculate()" id="month" class="quantity "
type="text" name="quantity" value="1"/>
<a class="incr-btn" data-action="increase" href="#"><i class="far
fa-plus-square"></i></i></a>
</div>
</div>
<div class="form-group">
<label for="s2id_autogen1" class="col-sm-2 control-label">
Select Room </label>
<div class="col-sm-6">
<select name="room_id" id="fee" class="form-control select2 select2-
offscreen" ">
<?php
include("connection.php");
$id = $_GET['id'];
$sql = "SELECT * FROM room ";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
?>
<!-- Fee is an int value and description is room name -->
<option id="fee" onchange="calculate()" value="<?php echo
$row['Fee']; ?>"><?php echo $row['Description']; ?></option>
<?php
}
}
?>
</select >
</div>
<span class="col-sm-4 control-label"> </span>
</div>
<div class="form-group">
Balance
<div class="col-sm-6">
<input type="text" id="result" class="form-control"
name="checkin_date" >
</div>
<span class="col-sm-4 control-label">
</span>
</div>
<div class="col-sm-offset-2 col-sm-8">
<input type="submit" class="btn btn-info" value="Add member">
</div>
</div>
Javascript :
<script>
function calculate() {
var myvar1 = document.getElementById('month').value;
var myvar2 = document.getElementById('fee').value;
var result = document.getElementById('result');
var myResult = myvar1 * myvar2;
document.getElementByid('result').value = myResult;
}
</script>
Your Javascript variables are all wrong...
You're setting myvar twice and then setting it to myBox1 * myBox2 which are never set.
I think what you're looking for is:
<script>
function calculate() {
var month_input = document.getElementById('month').value;
var fee_input = document.getElementById('fee').value;
var result = month_input * fee_input;
document.getElementById('result').value = myResult;
}
</script>
You will also want to remove id="fee" from all of your <option> tags. By default, the value of a select is the value of its option that is selected.
Try getting the value of the selected option like this. Run the snippet to see the result.
function calculate() {
var month_input = document.getElementById('month').value;
var select_fee = document.getElementById('fee');
var fee_input = select_fee.options[select_fee.selectedIndex].value
var result = month_input * fee_input;
document.getElementById('result').value = result;
}
label {
display: inline-block;
width: 70px;
}
input {
padding: 6px 14px;
}
.form-group {
padding: 8px;
}
<div class="form-group">
<label>Month:</label>
<input onchange="calculate()" id="month" class="quantity " type="text" name="quantity" value="1" />
</div>
<div class="form-group">
<label>Fees:</label>
<select name="room_id" onchange="calculate()" id="fee" class="form-control select2 select2-offscreen">
<option value="0"></option>
<option value="100">Option 1</option>
<option value="200">Option 2</option>
<option value="300">Option 3</option>
</select>
</div>
<div class="form-group">
<label>Result:</label>
<input type="text" id="result" />
</div>

Why oninput function not work under JavaScript?

My HTML code:
<div class="form-group col-sm-12">
<label for="input-text-help" >Select Vendor
</label>
<select name="vname" class="form-control">
<option value="">Select Vendor</option>
<?php
foreach($Fetchvendors as $Fetch){
?>
<option value="<?php echo $Fetch->id;?>"><?php echo $Fetch->name; ?>
</option>
<?php
}
?>
</select>
</div>
<div class="form-group col-sm-12">
<label for="input-text-help"> Date</label>
<input type="text" name="date" id="datepicker" class="form-control">
</div>
<table class="table">
<i class="fa fa-plus" style="margin-left:500px;">**Add More**</i>
<thead>
<th>Material Name</th>
<th>Quantity</th>
<th>Price</th>
</thead>
<tbody>
<tr >
<td>
<select name="mname[]" class="mname">
<option value=""> Select Material </option>
<?php
foreach($FetchMateril as $Fetch){
?>
<option value="<?php echo $Fetch->id;?>"><?php echo $Fetch->mname; ?></option>
<?php
}
?>
</select>
</td>
<td>
<input type="text" name="qty[]" class="quanitity" id="qty" placeholder="Material Unit">
<!--
<select name="qty[]" class="quanitity">
<option>Select Quanitity</option>
<?php for($i=1;$i<=50;$i++){?>
<option><?php echo $i;?></option>
<?php }?>
</select>
-->
</td>
<td>
<input type="text" name="price[]" class="price" id="**price**" *oninput="calculate()"*>
<input type="text" name="Totalprice[]" id="Totalprice" >
</td>
</tr>
</tbody>
</table>
<div class="form-group">
<div class="form-group">
<div class="col-sm-10">
<input type="submit" name="submit" class="btn btn-primary" id="input-text-help" style=" margin-left:300px;" >
</div>
</div>
</form>
</div>
</div>
In my html code have a option to add more row for multiple insert, When i click on add more option it add one row by javascript. in my input tage price oninput call calculate function, where calculate function calculate two input field and return in third field.
It Work on row one but in second row totalprice not work mean calculate not return any value in third field.
My question can oninput="calculate()" function under JavaScript like
My code when I am click Add more option
<script>
$(document).ready(function(){
//alert();
var i = 0;
$(".fa-plus").click(function(){
$(".table").append('<tr><td><select name="mname[]"
class="mname"><option>Select Material</option><?php foreach($FetchMateril as
$Fetch){?><option value="<?php echo $Fetch->id;?>"><?php echo $Fetch-
>mname;?></option><?php }?></select></td><td><input type="text" name="qty[]"
></td><td><input type="text" name="price[]" class="price" value=""></td>
</tr>');
i++;
});
});
</script>
My calculate function
function calculate() {
var myBox1 = document.getElementById('qty').value;
var myBox2 = document.getElementById('price').value;
var result = document.getElementById('Totalprice');
var myResult = myBox1 * myBox2;
//alert(myResult);
document.getElementById('Totalprice').value = myResult;
}
Try This May this will help you
$('#price').on('keyup', function(){
var myBox1 = document.getElementById('qty').value;
var myBox2 = document.getElementById('price').value;
var result = document.getElementById('Totalprice');
var myResult = myBox1 * myBox2;
document.getElementById('Totalprice').value = myResult;
});

Cloning Input Fields with Unique IDs

I have a form that I would like to have an user be able to add as many items to as they need. However, certain items require an AJAX call to retrieve information from a database, and that information be returned into fields. Currently, the replace destination is static, meaning that no matter what item calls the replace method, it will only change the first. I need it to change the one that called it. I've been stuck on this for three days, any help would be greatly appreciated!
Javascript:
ar uniqueId = 1;
function getAjax(seek, getId, destUrl, reset)
{
var xmlhttp;
if (seek=="")
{
document.getElementById(getId).innerHTML=reset;
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('m_width' + getId).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",destUrl+seek,true);
xmlhttp.send();
}
$(function() {
$('.addRow').click(function() {
var copy = $("#original").clone(true);
var formId = 'NewForm' + uniqueId;
copy.attr('id', formId );
copy.attr('name', formId );
$('#item').append(copy);
$('#' + formId).find('input,select,div').each(function(){
$(this).attr('id', $(this).attr('id') + uniqueId);
$(this).attr('name', $(this).attr('name') + uniqueId);
});
$('#NewForm').style.display = 'inline';
uniqueId++;
});
});
$(function() {
$('.removeRow').click(function() {
$(this).parent().remove();
});
});
HTML:
<div id="container">
<h3>item</h3>
<div id="item" class="item" >
<form action="" id="original">
<input type="text" class="" id="hidden" value="">
<select style="width: 160px" id="" name="" onchange="getAjax(this.value, 'm_width', 'm_width.php?media=','')">
<?php include 'includes/media.php'; ?>
</select>
<div id="m_width">
<label for="media_color_size">Width: </label>
<select id='media_color_size' style="width: 160px" disabled>
<option value="">None</option>
</select>
</div>
<select class="client" id="client" name="client" title="Client">
<option>Client1</option>
<option>Client2</option>
<option>Client3</option>
<option>Client4</option>
</select>
<input type="button" class="removeRow" value="Remove Row"/>
</div>
</form>
<input type="button" class="addRow" value="Add Row" />
</div>
and m_width.php:
<?php
require_once $_SERVER['DOCUMENT_ROOT']. '/dev/scripts/connect.php';
require_once $_SERVER['DOCUMENT_ROOT']. '/dev/scripts/authorize.php';
authorize_user();
$media = trim(strip_tags($_GET["media"]));
$query = "SELECT distinct material_id, width FROM media WHERE material_id = $media;";
$result = mysql_query($query);
echo "<label for='media_color_size'>Width: </label><br />";
echo "<select id='media_color_size' name='media_color_size' class='width' style='width: 160px'>";
echo "<option>Select Width</option>";
while ($row = mysql_fetch_assoc($result)) {
echo "<option value={$row['media_id']}>{$row['width']}</option>";
}
echo "</select>";
return;
?>
You can accomplish what you need to do without the use of unique IDs; there's too much unnecessary overhead. Class selectors would work fine. Here is my suggestion; if each form is inside a div.item element then use this to make the ajax call. Plus, you don't want to use inline JavaScript.
$('div.item form select').not('.client').on('change', function() {
//save a reference to the select element that triggered the change event
var that = $(this);
$.ajax({
url: '....',
....
success: function() {
//get the div.item ancestor of the select that triggered the change event
var divItem = that.closest('div.item');
//now change elements only within divItem
}
});
});
As you can see all this is accomplished without reference to any ID of any particular form. Therefore, you may not need to assign unique IDs to your forms.
PROOF OF CONCEPT DEMO:
$('div.item form select').not('.client').on('change', function() {
alert( $(this).closest( '.container' ).find( 'h3' ).text() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
<h3>item 1</h3>
<div id="item" class="item" >
<form action="" class="original">
<input type="text" class="hidden" value="">
<select style="width: 160px" id="" name="">
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
<div class="m_width">
<label for="media_color_size">Width: </label>
<select id='media_color_size' style="width: 160px" disabled>
<option value="">None</option>
</select>
</div>
<select class="client" name="client" title="Client">
<option>Client1</option>
<option>Client2</option>
<option>Client3</option>
<option>Client4</option>
</select>
<input type="button" class="removeRow" value="Remove Row"/>
</div>
</form>
<input type="button" class="addRow" value="Add Row" />
</div>
<div class="container">
<h3>item 2</h3>
<div id="item" class="item" >
<form action="" class="original">
<input type="text" class="hidden" value="">
<select style="width: 160px" id="" name="">
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
<div class="m_width">
<label for="media_color_size">Width: </label>
<select id='media_color_size' style="width: 160px" disabled>
<option value="">None</option>
</select>
</div>
<select class="client" name="client" title="Client">
<option>Client1</option>
<option>Client2</option>
<option>Client3</option>
<option>Client4</option>
</select>
<input type="button" class="removeRow" value="Remove Row"/>
</div>
</form>
<input type="button" class="addRow" value="Add Row" />
</div>
<div class="container">
<h3>item 3</h3>
<div id="item" class="item" >
<form action="" class="original">
<input type="text" class="hidden" value="">
<select style="width: 160px" id="" name="">
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
<div class="m_width">
<label for="media_color_size">Width: </label>
<select id='media_color_size' style="width: 160px" disabled>
<option value="">None</option>
</select>
</div>
<select class="client" name="client" title="Client">
<option>Client1</option>
<option>Client2</option>
<option>Client3</option>
<option>Client4</option>
</select>
<input type="button" class="removeRow" value="Remove Row"/>
</div>
</form>
<input type="button" class="addRow" value="Add Row" />
</div>

Categories