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
});
Related
Good day! I want to write an ajax request passing two variables to the controller. The problem is that I cannot get the values from the textboxes to my JavaScript
This is the JavaScript and the HTML code.
When I alert the day variable I get nothing it shows that the field is empty. I am very new to programming
$('#historic_form').submit(function(e) {
e.preventDefault();
var fund_id = $(this).val();
var day = $(this).val();
//data = $('#historic_form').serialize();
$.ajax({
url:'Search/Searchday',
type: 'POST',
dataType:'json',
data: {fund_id: fund_id, day: day},
error: function() {
alert(day);},
success: function(response) {
$("tbody").append("<tr><td>"+title+"</td><td>"+description+"</td></tr>");
}
});
});
And below are my HTML Codes
<select required id="member_id" name="member_id" class="form-control">
<option selected disabled>Select Member</option>
<?php for ($i=0;$i<$fMembers->num_rows();$i++){
echo "<option value='".$fMembers->row($i)->id."'>".$fMembers->row($i)->member_name."</option>";}?>
</select>
<select required class="form-control" id="fund_id" name="fund_id">
<option selected disabled>Select Fund</option>
</select>
<input type="date" required name="day" placeholder="Select a date" class="form-control datepicker hasDatepicker" data-dateformat="dd/mm/yy" id="histDate">
$('#historic_form').submit(function(e) {
Your event handler is triggered by a form submission, so inside the function this will refer to the <form>.
var fund_id = $(this).val();
var day = $(this).val();
<form> elements don't have values. You need to find() the <select> element you want to read the value from and call val() on that.
I am filling a data-list in html using data from a Json . The options are being appended to the data-list with the value and label text . on click of an option , I want the value and the text to be inserted into a form text field .
The value of the option can be accessed and is successfully inserted into the text field. But I am not able to access the label of the option to insert it.
I have tried using $(this).innerhtml(); , $(this).text(); , $(this).label(); , $(this).innerhtml(); and so on..
all of which turned out to return null value (undefined) instead of the required string.
$(document).ready(function ()
{
$.ajax({
type: 'POST',
url: '#Url.Action("MyJsonFunction")',
datatype: 'json',
success: function (data) {
$.each(data, function (index, data) { $("#myid1").append("<option value='"+data.Value+"'label='"+data.Text+"'></option > ");})},
error: function ()
{
alert("Something went wrong!");}});
$("#myid2").change(function ()
{
var s = $(this).val();
var d = $(this).html();
alert(d);
$("#input1").val(s);
$("#input2").val(d);
});
});
The value of the option is being inserted to the input text field but the label of the option is null when i try to access it .
when i alert it , it displays either an empty string or "undefined" .
$('body').on('change','#myid1',function(){ alert( $(this).find(':selected').attr('label') ) });
Please try this code. I am sure this will work
Try this solution.you have to make any one option as selected, because on form load,none of your options are selected and it will surely alert as undefined.
$(document).ready(function ()
{
$("#colors").trigger('change');
});
$("#colors").change(function () {
var d = $('#colors').find("option:selected").val();
alert(d);
$('#selvalue').val(d);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<label for="color">Favorite Color</label>
<input list="colors" name="color">
<datalist id="colors">
<option selected=selected value="Green">
<option value="Red">
<option value="Blue">
<option value="Yellow">
<option value="Orange">
</datalist>
<input type='text' id='selvalue' placeholder='Display seleted value'/>
I have a table about products. It has id, productdmc, productcode columns.
In this select menu, productdmc is showing.
When one item was selected, label its gonna change with related rows. Thats what i need. But i cant figure out the solution.
productcode.
<select class="form-control" name="productdmc" id="productdmc">
<option disabled selected>DMC</option>
#foreach ($product as $products)
<option value="{{ $products->productdmc }}">{{ $products->productdmc }}</option>
#endforeach
</select>
Related input
<input type="text" name="productcode" id="productcode">
This is the js code. I dont know this is working. This is my actual problem.
<script type="text/javascript">
$(document).ready(function() {
$('select[name="productdmc"]').on('change', function() {
var tmp = $(this).val();
if(tmp) {
$.ajax({
url: '/products/create/'+tmp,
type: "GET",
dataType: "json",
success:function(data) {
$('productcode').empty();
$.each(data, function(key, value) {
$('productcode').innerHTML('<input value="'+ key +'">');
});
}
});
}else{
$('productcode').empty();
}
});
});
</script>
In my Controller:
$val = DB::table("products")->pluck("productdmc","productcode");
return json_encode($val);
I know, i messed up so much. But codes are so complicated than this. I write this code in here(shorter version). Not copy-paste. I stucked here in a while. I cant find what is the real solution is.
I am open for all kinda solution.
Sorry for my bad english.
innerHTML is a property of HTML elements, not a function of jQuery's representation.
Use html(content) instead, and I think it should work:
$('#productcode').html('<input value="'+ key +'">');
Your selector is wrong, you forgot the '#'.
var $productCode = $('#productcode');
Also, when the event 'change' is triggered, you need to fetch the selected option.
var selectedValue = $element.find('option:selected').val();
HTML
<select class="form-control" name="productdmc" id="productdmc">
<option disabled selected>DMC</option>
#foreach ($product as $products)
<option value="{{ $products->productdmc }}">{{ $products->productdmc }}</option>
#endforeach
</select>
<input type="text" name="productcode" id="productcode">
Javascript:
<script type="text/javascript">
$(document).ready(function() {
$('body').on('change', 'select[name="productdmc"]', function(e) {
var $element = $(e.currentTarget); // $(this) is also fine.
// Get selected value
var selectedValue = $element.find('option:selected').val();
var $productCode = $('#productcode');
// No value selected
if (!selectedValue) {
$productCode.val('');
return;
}
$.ajax({
url: '/products/create/' + selectedValue,
type: 'GET',
dataType: 'json',
error: function() {
$productCode.val('');
},
success: function(res) {
$productCode.val('');
if (res.length < 1) return;
$productCode.val(res[0] || '');
// This will populate more than 1 field. So,
// I'm not sure about what you expect on the backend.
// If you want to populate more than 1,
// you should change the selector/field (do not use id in this case)
// $.each(res, function(key, value) {
// $productCode.val(key);
// });
}
})
});
});
</script>
PHP
<?php
$products = DB::table('products')->get();
return response(
$products->pluck('productdmc', 'productcode')->toArray()
);
You can read more about jQuery selectors here: https://api.jquery.com/category/selectors/
I want to create an autofill search box. it gets a JSON and sends them to an HTML5 <datalist> of <option>s.
It works fine but it cant use spaces in values! so it just returns the first word. for example, if the jresults.name is "lets go" - I get only "lets".
What is the best way doing this?
This part: $( "#prod_name_list" ).children().remove(); prevents me of choosing an option from the list. because it deletes everything in it when I "keyup" so I need a different solution for this.
The second part is after submitting the form I want to get the id chosen of the object. (jresults.id) and I'm not sure how to retrieve it with the submit.
MY CODE:
JS part:
$("#prod_name").bind("keyup", function(e) {
if (e.which <= 90 && e.which >= 48){
$( "#prod_name_list" ).children().remove();
var prod_name = $("#prod_name").val();
$.ajax({
method: "POST",
url: "<?php echo site_url('kas/search_prod_name'); ?>",
data: ({ "prod_name": prod_name }),
success: function (result){
var jresults = JSON.parse(result);
console.log("jresults: "+jresults);
var lng = jresults.length;
console.log("lng: "+lng);
for (var i=0; i<lng; i++) {
if (jresults.hasOwnProperty(i)) {
console.log("name: "+jresults[i].name);
$("#prod_name_list").append("<option name=\"prod_id\" id="+jresults[i].id+">"+jresults[i].name+"</option>");
}
}
}
});
}
});
HTML part(using codeigniter syntaxes for the form:
<?php
$attributes = array('class' => 'prod_name', 'id' => 'prod_name', 'name' => 'prod_name', 'list' => 'prod_name_list');
echo form_input('prod_name', 'prod Name', $attributes);
?>
<datalist id="prod_name_list">
</datalist>
A few things to work on here, but let's jump into a working example: https://jsfiddle.net/Twisty/a2z7e1yb/
The HTML I tested with:
Name: <input class="prod_name" id="prod_name" name="prod_name" list="prod_name_list" />
<datalist id="prod_name_list">
</datalist>
The JQuery I would advise using:
$(document).ready(function() {
$("#prod_name").keyup(function() {
$.ajax({
method: "POST",
url: "<?php echo site_url('kas/search_prod_name'); ?>",
data: {
"prod_name": $("#prod_name").val();
},
success: function(result) {
console.log(result);
var options = "";
$.each(result, function(k, v) {
console.log("name: " + v.name);
options += "<option value='" v.name + "'>\r\n";
});
console.log(options);
$("#prod_name_list").html(options);
}
});
});
});
As was mentioned, you can use onKeyPress versus onKeyUp. I leave that up to you.
I did testing with test data that looked like:
[
{
"name": "Lets Go"
}, {
"name": "Go More"
}
]
The $.each() works well for this. It will iterate over each array item and place it's Key into k and each object into v. We then generate a string of all the options and replace whatever is inside our datalist So if the result set is 15 options on the first character, it would be replaced ion the next keystroke with whatever result set we get.
Using .remove() and .append(), in my mind, becomes cumbersome for this type of application. You want to remove all the options, or replace them, with whatever new data you receive. In my working example, when a key is pressed, we see:
<datalist id="prod_name_list">
<option value="0">Lets Go</option>
<option value="1">Go More</option>
</datalist>
I hope this is clear and helps you out. If it's not, leave a comment and let me know.
Update
I think you may be using the <datalist> tag incorrectly. It should be fully populated when the page loads, not after text is entered. See more here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist
It should be used like so: https://jsfiddle.net/Twisty/a2z7e1yb/2/
<label>Name:
<input class="prod_name" id="prod_name" name="prod_name" list="prod_name_list" /></label>
<datalist id="prod_name_list">
<option value="Let's Go" />
<option value="No Go" />
<option value="Go Back to Bed" />
</datalist>
If you really want to make it like JQuery UI's Autocomplete, you would build a <ul> or <div> with the results as a list inside. This list would be populated when a key is pressed, showing just the relevant results. For example if "L" was pressed it would sen that value to your PHP which would show "Let's Go" and any other product Names that begin with "L". It's different than <datalist> which looks for anything in your List that contains "L".
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.