Ajax filter: Select + Radio button - javascript

i have problem with this script:
When I select a type from the select and choose the amount of the radio buttons, the value does not change, but if I choose a new type from the select, then the value is altered properly.
I wish that once you choose a type from the select, changing several times the amount, the price value change in real time.
Thank you in advance
HTML + PHP
<select name="tipo" id="tiposelect">
<option selected="selected"> --- </option>
<?
$sql_tipo = mysql_query("SELECT * FROM AM_Tipi_Prodotto_Agenzia WHERE id_prodotto = $id_prodotto");
while($row_tipo = mysql_fetch_array($sql_tipo)){
?>
<option value="<?=$row_tipo['nome_prodotto']?>"><?=$row_tipo['nome_prodotto']?></option>
<? }?>
</select>
</div>
<div class="point-of-action">
<h5>Quantità:</h5>
<?
$sql_quantita = mysql_query("SELECT * FROM AM_Quantita_Prodotti_Agenzia WHERE id_prodotto = $id_prodotto LIMIT 3");
while($row_quantita = mysql_fetch_array($sql_quantita)){
?>
<input type="radio" name="quantita_2" value="<?=$row_quantita['quantita']?>"> <?=$row_quantita['quantita']?>
<? }?>
</div>
AJAX
<script>
$(document).ready(function () {
//RADIO BUTTON
$("input[name='quantita_2']").change(function() {
var value=$("input[name='quantita_2']:checked").val()
//SELECT
var tipo;
$("#tiposelect").change(function(){
tipo = $('#tiposelect').val();
$.ajax({
method: "POST",
url: "calcolo_agenzia.php",
data: { id_prodotto: <?php echo (isset($_REQUEST['id_prodotto']) ? $_REQUEST['id_prodotto'] : 0) ; ?>, quantita: value, tipo: tipo },
success: function( msg ) {
$("#importoCalcolato2").text("€"+msg);
}
});
});
});
});
</script>
FORM IMAGE

try changing $("#tiposelect").change(function(){ to $("#tiposelect").click(function(){ this will triger event every time toy click on $('#tiposelect')
Additionally you can also add another event handler to for $('#tiposelect').click() so that which ever changes will trigger ajax

Try following code
$("input[name='quantita_2']").on("change",function() {
//your code
}
Update:
check your tipo variable. It gets value only on change event of select. It's initial value should be the value of selected option.

Related

How to show selected value using javascript in laravel

i want to show the selected value to the select option, the value actually selected but cannot show that value on select option form.
for example i have a 3 value it can be choose is anyaman, cendana, and bakulan. when 1 edit that form with value cendana, the showed value is the first sequence (anyaman) but when i open that select option that focused on the true data value (cendana).
This is HTML Script :
<div class="mb-1">
<label class="form-label" for="user-role">Asal Kelompok</label>
<select id="editkelompok_id" name="kelompok_id" class="select2 form-select">
<option disabled="" value=""> <b> Pilih asal kelompok </b></option>
#foreach($kelompok as $data)
<option value="{{$data->id}}">{{$data->nama_desa}} - {{$data->nama_kelompok}} </option>
#endforeach
</select>
</div>
The Controller
public function detaildataanggota($id)
{
$status = anggota::findOrfail($id);
return $status;
}
Java Script
<script type="text/javascript">
function detaildataanggota(id){
$.ajax({
url: "{{url('admin/pendataan/dataanggota/detail')}}" + "/" + id,
dataType: "json",
success: function(status) {
$('#editid').val(status.id);
$('#editnama_anggota').val(status.nama_anggota);
$('#editnik').val(status.nik);
$('#editjabatan').val(status.jabatan);
$('#editjenis_kelamin').val(status.jenis_kelamin);
$('#edittanggal_lahir').val(status.tanggal_lahir);
$('#editalamat').val(status.alamat);
$('#editkelompok_id').val(status.kelompok_id);
},
});
}
</script>
The problem is on #editkelompok_id
Try this
let select = $('#editkelompok_id');
select.on('change',()=>{
// Your stuff
})
or
let options = $('#editkelompok_id').children();
options.each(function() {
let option = $(this);
option.on('change', () => {
select.val(option.val());
})
})
I hope it was useful

How to add select boxes dynamically through add button then save the values in mysql through php

Okay My problem is little complex which I am unable to solve. I already have two select boxes in which the options are coming from Database Mysql through php. Like when I select an option in Select Box#1, Select Box#2 gets updated through ajax and displays the options against SelectBox#1 from MYSQL Database. I am able to store the values from those two in database as well.
Problem
:
Now the problem is that I want a button like "Add New" that should create same two select boxes with same functionality the number of times i click Add New Button. Example: I filled the original two select boxes, then I click Add New and two new select boxes gets generated.. I fill them and again click Add New and two more select boxes gets generated so total of 6 select boxes with same first Select Box options but options in Second Select Box may differ according to the option selected in first select box. Now, two things I need help in:-
1. How to perform this Add New button thing that generates select boxes with same functionality as the original ones i.e Select Option from First Select Box, Second Select Box gets auto updated according to the option selected in first select box and the options are fetched from Database.
2. How do I read and store those values selected from new fields? I am able to read and store values that were passed from the original two select boxes but how about the new ones? Any unique names or ids of new select boxes I generate through button or some sort of array etc?
Here is my code that I used for my first two select boxes:-
HTML FILE-TOP
function load_country()
{
$connection = new mysqli("localhost","root","","test");
$query = "SELECT * FROM country";
$result = mysqli_query($connection,$query);
while($row = mysqli_fetch_array($result))
{
$output .= '<option value="'.$row["c_id"].'">'.$row["c_name"].'</option>' ;
}
return $output;
}
HTML FILE-INSIDE
<form method="post">
<p> <select name="country" id="country">
<option value="">Select Country</option>
<?php echo load_country() ?>
</select> </p>
<p> <select name="city" id="city">
<option value="">Select City</option>
</select> </p>
<input type="submit" name="submit" value="submit">
</form>
Jquery/Ajax Function that updates the Second Select Option:-
$(document).ready(function(){
$('#country').change(function(){
var country_id = $(this).val();
$.ajax({
url:"fetch_city.php",
method:"POST",
data:{
"c_id":country_id
},
dataType: "text",
success:function(data)
{
$('#city').html(data);
}
});
});
});
</script>
PHP File used by Ajax to Update Second Select Box:-
$output = '';
$query = "SELECT * FROM cities WHERE country_id = '{$_POST["c_id"]}'";
$result = mysqli_query($connection,$query);
$output = '<option value="">Select City</option>';
while($row = mysqli_fetch_array($result))
{
$output .= '<option value="'.$row["city_id"].'">'.$row["city_name"].'</option>' ;
}
echo $output;
First Change the HTML into something like this, use classes and ids for finding objects better:
<form method="post">
<div id="form-area">
<div class="select-box" id="box_1">
<p>
<select class="country" name="country[]">
<option value="">Select Country</option>
<?php echo load_country() ?>
</select>
</p>
<p>
<select class="city" name="city[]">
<option value="">Select City</option>
</select>
</p>
</div>
</div>
<button id="add_new" type="button"> [+] </button>
<input type="submit" name="submit" value="submit">
</form>
javascript:
$(document).on("change", ".country", function() {
var current_box = $(this).parent().closest('div').attr('id');
var country_id = $(this).val();
$.ajax({
url: "fetch_city.php",
method: "POST",
data: {
"c_id": country_id
},
dataType: "text",
success: function(data) {
$('#' + current_box).find(".city").html(data);
}
});
});
var id = 1;
$('#add_new').click(function() {
id++;
$(".select-box:last").clone().attr("id", "box_" + id).appendTo("#form-area");
});
After that, you should handle Array input in PHP form destination code.
In your case it should be something like this:
$cities = $_REQUEST['city'];
$cuontries = $_REQUEST['cuontry'];
foreach( $cuontries as $key => $cuontry ) {
$row[] = [ "cuontry" => $cuontry , "city" => $cities[$key] ];
}
This array is as same as form array that you created with [+] button in HTML

How to display data from selecting option in drop down

From my device table, I have device id, device name and image id and my drop down currently displays the the respective devices. How can I display the image id that is respective to the device selected on. I've tried messing around the code but I'm still going no where.
<select class = "form-control" id="changeDevice" name="changeDevice" >
<option value= " -- select a device -- " disabled selected value> -- select a device -- </option>
<?php
foreach($device as $devicedrop){
?>
<option value="<?php echo $devicedrop['id'] ?>">
<?php echo $devicedrop['name'] ?> </option>
<?php
}
?>
</select>
<input type = "text" id="text"></input>
<script>
$('#changeDevice').find('option:selected').text();
var text = $(this);
$('#text').prop(text);
</script>
take 'selectedIndex' property of select element. and...
<script>
var device = $('#changeDevice');
var selectedIndex = device.prop('selectedIndex');
var text = $('option', device).eq(selectedIndex).text().trim();
$('#text').val(text);
</script>
---- Edit
Well. It's you again Lotse. :)
You can store your data into DOM element (option) like...
<?php
$rows = ...;
foreach($rows as $row) {
printf('<option value="%d" data-image-id="%d" data-image-name="%s" data-device-name="%s">%s</option>', $row['id'], $row['image_id'], $row['device_name'], ...);
}
?>
this code generate HTML as
<select id="#device_option">
<option value="1" data-image-id="32" data-image-name="sample-01.jpg" data-device-name="some name">...</option>
...
</select>
then, now you can pick up any data from jQuery's $.data(key) function.
<script>
$(function() {
$('device_option').on('change', function() {
var options = $('option:selected', this); // take care when multiselect on
var val = $(this).val(); // or options.val()
var image_id = options.data('image-id');
var image_name = options.data('image-name');
var device_id = options.data('device-name');
var text = options.text().trim();
// you can poll data from DOM
});
});
</script>
http://www.w3schools.com/tags/att_global_data.asp
https://api.jquery.com/selected-selector/
https://api.jquery.com/data/

How to fill Textbox using dropdownlist

Please help me.. i have dropdownlist which i have populated from the database table, now i want to fill textbox from the database list...
i have one table
id | juice | rupees
now when i select Mango Juice from juice column from dropdownlist it should show the cost of Mango Juice in textbox by retrieving from rupees column
here is the dropdownlist which is populated from the table
<select name="drink" id="drinkid">
<option id="0">-- Select the drink --</option>
<?php
require("dbcon.php");
$getalldrinks = mysql_query("SELECT * FROM tableone");
while($viewalldrinks = mysql_fetch_array($getalldrinks)){
?>
<option id="<?php echo $viewalldrinks['id']; ?>"><?php echo $viewalldrinks['juice'] ?></option>
<?php
}
?>
</select>
and here is the textbox
<input type="text" name="juicename" id="juiceid" placeholder="Juice">
Please help me.. thanks in advance.
First add onChange() event to your select tag to call function fillTextBox() every time you change option, then the function will fill the textbox:
<select name="drink" id="drinkid" onChange="fillTextBox()">
Now you have to get rupees column & store it in every option using data attribute :
<option data-rupees="<?php echo $viewalldrinks['rupees']; ?>" id="<?php echo $viewalldrinks['id']; ?>" ><?php echo $viewalldrinks['juice'] ?></option>
Create the function fillTextBox() that will fill the textbox by rupees value of selected option :
function fillTextBox(){
var myselect = document.getElementById("drinkid");
var rupees = myselect.options[myselect.selectedIndex].getAttribute("data-rupees");
document.getElementById("juiceid").value = rupees;
}
That should do the work, hope this helps.
You'll need to use javascript to detect changes in your select box, store those values, and then populate the text box with the desired values. You haven't listed a text box in your html, so I'll have to assume that I can access this value using input[type=text]. Here's an approximation of what your javascript should look like given that I am working with incomplete information. Note that your should probably contain an attribute called value to store your id instead of using the id attribute.
var el = document.getElementById('drinkId');
el.addEventListener("click", function(){
var data = {"id": el.value, "text": el.innerHTML};
document.querySelectorAll('input[type=text]')[0].value = data.text;
});
You'll need to provide more detail and more of your code if you want an exact solution to your problem.
UPDATE: I see you've added the text box HTML, so here's the updated version of the event handler:
var el = document.getElementById('drinkId');
el.addEventListener("click", function(){
var data = {"id": el.value, "text": el.innerHTML};
document.getElementById('juiceId').value = data.text;
});

Get select selected value

I have a url like this:
index.php/home/lista_modelo_ajax?id="+$('#colecoes').val(),
The thing is that the: $('#colecoes').val() is always the first item of the select, not the one I choose.
Any ideas?
Thanks in advance.
EDIT
<script>
$(function() {
$( "#modelos" ).autocomplete({
source: "<?php echo base_url();?>index.php/home/lista_modelo_ajax?id="+$('#colecoes').val(),
minLength: 2
});
});
</script>
<label for="colecoes">Coleções</label>
<select name="colecoes" id="colecoes">
<option value="16">-</option>
<?php foreach($lista_colecao as $colecao){?>
<option value="<?php echo $colecao->idColecao;?>"><?php echo $colecao->nomeColecao;?></option>
<?php }?>
</select>
<label for="modelos">Modelo</label>
<input type="text" name="modelos" id="modelos" />
All php is working fine, generating the IDs on the value of options objects, the problem is only with JS
This will depend on where you are writing this code. If you are writing it directly in the document ready that would be normal as at the moment this code executes that's the selected value. On the other hand if you are writing it for example in the .change event of the dropdown list you will get the actual value:
$('#colecoes').change(function() {
var id = $(this).val(); // now you will get the actual selected value
$.ajax({
url: 'index.php/home/lista_modelo_ajax',
data: { id: id },
success: function(result) {
...
}
});
});
Just do:
$('#colecoes').val(); //assuming `colecoes` is the id of the select
Example with onchange:
$('#colecoes').change(function(){
alert(this.value); //alerts the selected option
});

Categories