Cloning Input Fields with Unique IDs - javascript

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>

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>

My variables aren't passing to the function

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.

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>
...

onchange event not working in firefox

in this piece of code i have 2 dropdown lists. one is department and the other is section name. on the basis of department i am changing my section name accordingly and then pushing these two dropdown list's values into my form's input.
The problem is that onchange event is working fine in chrome but not in firefox if you use keyboard(tab key and arrow keys) only. how can i fix this without adding jquery??
function fields(){
var seldprt = document.getElementById("seldprt");//seldprt is for Department
var section = seldprt.value;//assigning the value of Department dropdown list to section variable
var dprt_input=section;
var input_Department=document.getElementById("departmentinput");
input_Department.value=dprt_input;
if(section=="REGULATORY")
{
document.getElementById("LEGALDiv").style.display="none";
document.getElementById("REGDiv").style.display="";
var subsection=document.getElementById("REGDiv_subcatagory");
var sub_catagory_input=subsection.value;
var input_Subcatagory=document.getElementById("subcatagoryinput");
input_Subcatagory.value=sub_catagory_input;
}
else if(section=="LEGAL")
{
document.getElementById("LEGALDiv").style.display="";
document.getElementById("REGDiv").style.display="none";
var subsection=document.getElementById("LEGALDiv_subcatagory");
var sub_catagory_input=subsection.value;
var input_Subcatagory=document.getElementById("subcatagoryinput");
input_Subcatagory.value=sub_catagory_input;
}
}
<div class="departmentdiv" onclick="fields()"><!-- here the function field is called on onclick event -->
<label>Department Name:</label>
<div align="right" class="selectdiv">
<select id = "seldprt" onfocus="fields();" onchange="fields();" onkeypress="fields();">
<option value = "LEGAL">LEGAL</option>
<option value = "REGULATORY">REGULATORY</option>
</select>
</div>
</div>
<div id="REGDiv" class="subcatagorydiv" style="display:none" >
<label>Section Name:</label>
<div align="right" class="selectdiv">
<select id = "REGDiv_subcatagory" onfocus="fields()" onchange="fields()" onkeypress="fields()">
<option value = "GLT">GLT</option>
<option value = "REGULATORY">REGULATORY</option>
</select>
</div>
</div>
<div id="LEGALDiv" class="subcatagorydiv" style="display:none" >
<label>Section Name:</label>
<div align="right" class="selectdiv" >
<select id = "LEGALDiv_subcatagory" onfocus="fields()" onchange="fields()" onkeypress="fields()">
<option value = "GLT">GLT</option>
<option value = "LEGAL">LEGAL</option>
</select>
</div>
</div>
<form action="" method="post" >
<div class="entry" onclick="previous_values()" style="">Name</div>
<input type="text" style="" name="name" id="departmentinput">
<div class="entry" style="" onclick="previous_values()">Section Number</div>
<input type="text" style="" name="Section" id="subcatagoryinput">
<div id="readwrite_buttons" class="hide">
<button id="ok" onclick="document.forms[0].submit();return false;">OK</button>
<button id="cancel" onclick="javascript:window.close();return false;">Cancel</button>
</div>
<div id="readonly_buttons" class="hide">
<button id="back" onclick="javascript:window.close();return false;">Back</button>
</div>
</form>
The onkeyup event should do what you're trying to do. It's could potentially generate a lot of events, so I would consider carefully whether it's really necessary. I saw that you tried the onkeypress event in your snippet. For reasons unknown to me, at least in firefox, it doesn't seem to catch the up/down arrows while onkeyup and onkeydown apparently do.
function fields(){
var seldprt = document.getElementById("seldprt");//seldprt is for Department
var section = seldprt.value;//assigning the value of Department dropdown list to section variable
var dprt_input=section;
var input_Department=document.getElementById("departmentinput");
input_Department.value=dprt_input;
if(section=="REGULATORY")
{
document.getElementById("LEGALDiv").style.display="none";
document.getElementById("REGDiv").style.display="";
var subsection=document.getElementById("REGDiv_subcatagory");
var sub_catagory_input=subsection.value;
var input_Subcatagory=document.getElementById("subcatagoryinput");
input_Subcatagory.value=sub_catagory_input;
}
else if(section=="LEGAL")
{
document.getElementById("LEGALDiv").style.display="";
document.getElementById("REGDiv").style.display="none";
var subsection=document.getElementById("LEGALDiv_subcatagory");
var sub_catagory_input=subsection.value;
var input_Subcatagory=document.getElementById("subcatagoryinput");
input_Subcatagory.value=sub_catagory_input;
}
}
<div class="departmentdiv" onclick="fields()"><!-- here the function field is called on onclick event -->
<label>Department Name:</label>
<div align="right" class="selectdiv">
<select id = "seldprt" onfocus="fields();" onchange="fields();" onkeypress="fields();">
<option value = "LEGAL">LEGAL</option>
<option value = "REGULATORY">REGULATORY</option>
</select>
</div>
</div>
<div id="REGDiv" class="subcatagorydiv" style="display:none" >
<label>Section Name:</label>
<div align="right" class="selectdiv">
<select id = "REGDiv_subcatagory" onfocus="fields()" onchange="fields()" onkeyup="fields()">
<option value = "GLT">GLT</option>
<option value = "REGULATORY">REGULATORY</option>
</select>
</div>
</div>
<div id="LEGALDiv" class="subcatagorydiv" style="display:none" >
<label>Section Name:</label>
<div align="right" class="selectdiv" >
<select id = "LEGALDiv_subcatagory" onfocus="fields()" onchange="fields()" onkeyup="fields()">
<option value = "GLT">GLT</option>
<option value = "LEGAL">LEGAL</option>
</select>
</div>
</div>
<form action="" method="post" >
<div class="entry" onclick="previous_values()" style="">Name</div>
<input type="text" style="" name="name" id="departmentinput">
<div class="entry" style="" onclick="previous_values()">Section Number</div>
<input type="text" style="" name="Section" id="subcatagoryinput">
<div id="readwrite_buttons" class="hide">
<button id="ok" onclick="document.forms[0].submit();return false;">OK</button>
<button id="cancel" onclick="javascript:window.close();return false;">Cancel</button>
</div>
<div id="readonly_buttons" class="hide">
<button id="back" onclick="javascript:window.close();return false;">Back</button>
</div>
</form>

passing data through text box from select option into another page

I am trying to pass data through a text box which is selected through the 'other' in select option. However, when I run the program, the data is not passed. Any ideas how to resolve this? here is the code that I am using. I have added most of the code below. I have to pass information through the select option in the form of a text box. However the information is not passed. Is there any other method that can do this, passing through text to another page?
<?php include_once("header.php"); ?>
<?php
$q_sel = "select * from tbl_drug";
$r_sel = mysql_query($q_sel);
?>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$('#my_textarea').hide();
$('#Quantity').change(function()
{
var o = $(this).find('option:selected').val();
console.log(o);
if(o=='other') $('#my_textarea').show(); else $('#my_textarea').hide();
});
});
</script>
</head>
<body style="background-color: #25383c;background-image: url(img/background.png);">
<?php include_once("nav.php"); ?>
<h1> Medication Appropriateness Index</h1>
<div class="container-fluid">
<div class="row">
<div class="col-sm-12">
<div class="well">
<form class="form-horizontal" role="form" action="save_drug.php" method="post">
<div class="form-group">
<label class="control-label col-sm-2">Drug:</label>
<div class="col-xs-3">
<select name="drug" id="Drug" class="form-control" required="">
<option value="" selected="" disabled="">Please select A drug...</option>
<?php
while($r1 = mysql_fetch_array($r_sel))
{ ?>
<option value="<?php echo $r1['d_id']; ?>"><?php echo $r1['drug_name']; ?></option>
<?php
}
?>
</select>
</div>
</div>
<script>
$(function() {
$("#dose").tooltip();
});
</script>
<div class="form-group">
<label class="control-label col-sm-2">Route:</label>
<div class="col-xs-3">
<select id="Quantity" name="quantity" class="form-control" required="">
<option value="" selected="" disabled="">Please select A dosage...</option>
<option value="PO">PO</option>
<option value="IV">IV</option>
<option value="PR">PR</option>
<option value="Topically">Topically</option>
<option value="other">Other (please specify)</option>
</select>
<textarea name="my_textarea" id="my_textarea"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="hidden" name="patient_id" value="<?php echo $_GET['patient_id']; ?>">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
always use 'name' attribute for inputs , because only name can send data on submit.
<textarea name="my_textarea" id="my_textarea"></textarea>

Categories