jquery .change multiple textbox and select retrieve data from row to row - javascript

I have a code that will display select and textbox depending on the count of the loop. The select dropdown will display currencies on acronym format if selected example USD the textbox will display "US Dollars". on the second loop if I select JPY it will display Japan Yen on the textbox on the second row and so on. Is this possible on jquery?
Here is my code
<script>
$(document).ready(function(){
$('#acr').change(function(){
//get json + this.value get corresponding value on db
//retrieve data
});
});
</script>
<?php
foreach($data as $d) {
?>
<select name = "acr" id = "acr">
//Records from db
</select>
<input type = "text" readonly value = ""> <br>
<?
}
??

Yes. But first please give a name attribute to your textbox and assume its id is 'longName'. You may have two options:
option 1:
Save the currencies short name/Long name in select. JPY
code:
$('#acr').change(function(){
$('#longName').val($(this).val());
});
option 2:
$('#acr').change(function(){
var sel = $(this);
$.ajax({
url: "your url",
type: "POST",
data: 'data='+sel.val(),
dataType:'json',
success: function(data) {
//Do what ever you want. Data holds the response from server
},
error: function() {
//Error occured, handle it
}
});
});
Read more on ajax here

Related

cant set selected value on select2 javascript ajax mode

i have a select2 element that load data from database using ajax. i want to load the value from db and select it as selected value in edit mode.
but im not able to load the value using trigger function.
i tried using looping by comparing selected values but i got the select2 option orinted twice.
$(document).ready(function(){
var area = $('#area').select2({
placeholder: "Pilih Cabang Area Tagih Collector Agency...",
multiple: true,
allowClear: true,
width: 'resolve'
});
var k;
var selected = [];
//imloading the value from db and insert it into an array
<?php foreach($area_coll as $area){
?>
selected.push("<?php echo $area->group_branch_id;?>");
<?php
}?>
$.ajax({
url: "<?php echo base_url();?>ama/c_agency/populate_dropdown_cabang",
type: 'GET',
success: function(data) {
var html = '';
var j;
data = JSON.parse(data);
//looping cabang
for(j=0; j<data.length; j++){
$('#area').append($('<option>').val(data[j].GroupBranchID).text(data[j].branch));
}
}
});
//this function not working at all
area.val(selected).trigger("change");
});
im not getting any error with this code nor the value still not selected.
Select2 have ajax options.
So I think you can use ajax directly as an options of select2 (reference: https://select2.org/data-sources/ajax#default-pre-selected-values)
The document said:
To provide default selections, you may include an <option> for each selection that contains the value and text that should be displayed:
<select class="js-example-data-ajax form-control">
<option value="3620194" selected="selected">select2/select2</option>
</select>
Mean that at the options you can push selected="selected" at edit page when option is stored on exist record.
Hope it help. thanks

JQuery chosen plugin - Sending the user typed input to an Ajax call

I am trying to populate the drop down using Chosen plugin for multiple select.
I have added the fiddle
http://jsfiddle.net/san1234/ymnj12xk/
My intention is to populate the "options" tag in the "select" tag, basing on JSON data obtained by sending user typed letter via the Ajax call.
For this I need to know, how to make an ajax call onkeyup i.e. if the user typed "Am", i want to send that input to an Ajax call and get the JSON response, something like ["America","Amsterdam"]
I'm new to this and I cant figure out a way to extract the user typed input in the 'select' box to actually send it as request in an Ajax call.
I have tried doing this but 'autocomplete' method in the JS file doesn't work
How do i do this? kindly help!
JS file
$(".chosen-select").chosen();
$(".chosen-select-deselect").chosen({
allow_single_deselect: true
});
$('.chosen-choices input').autocomplete({
source: function(request, response) {
$.ajax({
url: "/someURL/" + request.term + "/",
dataType: "json",
beforeSend: function() {
$('ul.chosen-results').empty();
},
success: function(data) {
alert("Success!");
response($.map(data, function(item) {
$('ul.chosen-results').append('<li class="active-result">' + item.name + '</li>');
}));
}
});
}
});
<link href="http://harvesthq.github.io/chosen/chosen.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://harvesthq.github.io/chosen/chosen.jquery.js"></script>
<select class="chosen chosen-select" multiple="" data-placeholder="Choose a Country" style="width:200px">
<option value="America">America</option>
<option value="Amsterdam">Amsterdam</option>
<option value="Australia">Australia</option>
<option value="Dallas">Dallas</option>
<option value="GHI">hij</option>
</select>
I dont know if you are using PHP in your back end or any other program language but here's my solution using php and javascript :
First your javaScript:
//initialization of chosen select
$(".chosen-select").chosen({
search_contains: true // an option to search between words
});
$(".chosen-select-deselect").chosen({
allow_single_deselect: true
});
//ajax function to search a new value to the dropdown list
function _ajaxSearch (param){
return $.ajax({
url: "request.php",
type: "POST",
dataType: "json",
data: {param:param}
})
}
//key event to call our ajax call
$(".chosen-choices input").on('keyup',function(){
var param = $('.chosen-choices input').val();// get the pressed key
_ajaxSearch(param)
.done(function(response){
var exists; // variable that returns a true if the value already exists in our dropdown list
$.each(response,function(index, el) { //loop to check if the value exists inside the list
$('#mySelect option').each(function(){
if (this.value == el.key) {
exists = true;
}
});
if (!exists) {// if the value does not exists, added it to the list
$("#mySelect").append("<option value="+el.key+">"+el.value+"</option>");
var ChosenInputValue = $('.chosen-choices input').val();//get the current value of the search
$("#mySelect").trigger("chosen:updated");//update the list
$('.chosen-choices input').val(ChosenInputValue);//since the update method reset the input fill the input with the value already typed
}
});
})
})
your php file:
if (isset($_POST["param"])) {// check is the param is set
$param = $_POST["param"]; // get the value of the param
$array = array('JKL' => 'jkl' , 'MNO'=>'mno', 'PQR'=>'pqr','STU'=>'stu','VWX'=>'vwx','YZ'=>'yz' );//array of values
$matches = array();//array of matches
foreach($array as $key=>$value){//loop to check the values
//check for match.
if(strpos($value, $param) !== false){
//add to matches array.
$matches[]= array ("key"=> $key,"value"=>$value);
}
}
//send the response using json format
echo json_encode($matches);
}
Hope it helps

Adding single hidden input value to each form input in ajax call

I have a form with a button that can add dynamic input fields, and it's creating an ajax issue. My ajax post is giving me 500 errors
But My console log for data right now is this:
but I need to insert these as
insert into ticker_content (ticker_id, content)
values (1, 'one'), (1, 'two');
If that makes sense.
So basically, the problem is i have multiple inputs at any given time (containing text values) and a hidden input in the form that gives me my correct ticker ID.
However, I need to make my array contain elements that each have the input text value and the ticker ID. So for every input that's created and filled, I need to assign the value of that form's hidden input to it as well so I can sent them as pairs to my foreach loop and insert.
Here's my addticker.php that's being called for the insert:
$items = $_POST['Items'];
$tickerID = $_POST['tickerID'];
foreach ($items as $item){
$addTicker = "
INSERT INTO ticker_content (tickerID, content)
values ('$tickerID', '$item');
"
$mysqlConn->query($addTicker);
}
So basically for every Items[] value, I need to insert with the same hidden field.
Here's my form and JS code for reference. The first JS block is mainly for the functionality of dynamically adding inputs, but the last JS block is the ajax using serializeArray();
<?php foreach($tickerDisplays as $key => $ticker):?>
<form id="Items" method="post">
<label id="ItemLabel">Item 1: </label>
<input type="text" name="Items[]"><br/> <!--form starts with one input-->
<button type="button" class="moreItems_add">+</button> <!--button dynamically adds input, up to 10 per form-->
<input type="hidden" name="tickerID" id="tickerID" class="tickerIdClass" value="<?php echo $ticker['ticker'] ?>"><!--hidden input used for tickerID-->
<input type="submit" name="saveTickerItems" value="Save Ticker Items"> <!--submit button-->
</form>
<?php endforeach;?>
<!-- This is the functionality for each form to click the '+' button and create new inputs -->
<script type="text/javascript">
$("button.moreItems_add").on("click", function(e) {
var tickerID = $(this).closest('form').find('.tickerIdClass').val(); //get value of hidden input for form
var numItems = $("input[type='text']", $(this).closest("form")).length;
if (numItems < 10) {
var html = '<label class="ItemLabel">Item ' + (numItems + 1) + ': </label>';
html += '<input type="text" name="Items[]"/><br/>';
$(this).before(html);
console.log(tickerID);
}
});
</script>
<!-- This is the ajax call to send all filled out and created inputs from form along with the hidden input -->
<script type="text/javascript">
$("#Items").submit(function(e) {
e.preventDefault();
var data = $("#Items").serializeArray();
console.log(data);
$.ajax({
type: "POST",
url: "addticker.php",
data: $("#Items").serializeArray(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
</script>
Firstly, you are missing a semicolon in your code (which is likely causing your 500 error).
Secondly, if you want to bundle all the fields from the form as a single query, the following will build out a query similar to what you noted earlier in your question as:
INSERT INTO ticker_content (ticker_id, content) VALUES(1, 'one'), (1, 'two'), ...
$items = $_POST['Items'];
$tickerID = $_POST['tickerID'];
$addTicker = "INSERT INTO ticker_content (tickerID, content) values";
foreach ($items as $item){
$addTicker .= "('$tickerID', '$item'),";
}
$addTicker = substr($addTicker, 0, -1); // Eat that last comma
$mysqlConn->query($addTicker);
Your HTML also needs some work because the id attribute should be unique on the page. Since you are duplicating the form, you should do something like the following:
<form id="Items<?php echo $ticker['ticker']?>" class="tickerform" method="post">
And then update your javascript:
// Using $(this) in Jquery allows you to access the
// element that is making the method call (in this case, the form)
$(".tickerform").submit(function(e) {
e.preventDefault();
var data = $(this).serializeArray();
console.log(data);
$.ajax({
type: "POST",
url: "addticker.php",
data: data, // Don't need to serialize again, 'var data' is still in scope.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});

Yii array helper selecting already set value from database

Am using array helpers if data exists i want to select the value...here product category master id is a foreign key in product master table.
A modal gets called on edit button and it uses the same modal as create button
but the fields are populated using hidden input field.
I want to select the already set value from the database.
$("#productmaster-product_category_master_id").val(data.product_category_master_id);
The above code is not working.
<?= $product_form->field($form_product_model, 'product_category_master_id')->dropDownList(
ArrayHelper::map(ProductCategoryMaster::find()->all(),'id','category'),['prompt'=>'','class'=>'form-control select2','style' => 'width:100%;height:80% !important']
);?>
function editProduct(id) {
console.log(id);
$.ajax
({
type:"GET",
url: "<?= Yii::getAlias('#web')?>/product-category-master/product?id="+id,
cache: false,
dataType:"json",
success: function(data)
{
console.log(data);
$('#sourceproduct').click();
$("#newid").val(data.id);
$("#productmaster-product_category_master_id").val(data.product_category_master_id);
//document.getElementById("editbutton").showModal();
//var myArr = JSON.parse(data);
return false;
}
});
}
Found the solution i just had to put
$('#productmaster-product_category_master_id').val(data.product_category_master_id).trigger('change');
instead of
$('#productmaster-product_category_master_id').val(data.product_category_master_id);

On page load call change events?

On page load I need to call change events for the drop down list. Currently what happens is in my Jquery code below when you select a value from the professions drop down list i.e. GP a Help text then below the drop down shows in a DIV area shows, however once you submit the form and if validation is thrown the help text goes from the view.
I need to call change events for the drop down list #profession but not exactly sure how to do this. Please advise
$('#profession').on('change', function (e) { //Gets the ID of profession drop down list
var selectedVal = $(this).val(); //Variable selectedVal this . value
$.ajax({ //Ajax declared
type: 'GET', //Its a get
url: "#Url.Action("GetenquiryTypes", "UnauthEnquiry")", //It goes to the enquiry controller method GetenquiryTypes
dataType: 'json', //Datatypes JSON
data: { SelectedProfession: selectedVal }, //data is SelectedProfession: selectedVal
success: function (json) { //Jquery Parse Json data from server on ajax success
if (json.helptext != undefined && json.helptext != '')
{
$('#ProfHelp').html(json.helptext)
$('#ProfHelpAlert').show(); ///////
}
else
$('#ProfHelpAlert').hide(); ///////
var targetDropdown = $('#enquirytype') //Var targetDropDropdown goes to dropdown ID enquiry type
targetDropdown.empty(); //target empty dropdown
$("<option />", {
val: "",
text: "Please select enquiry type" //Select enquiry type
}).appendTo(targetDropdown); //add to the target dd
if (json.enquiryTypes.length > 0) { //if JASON data from server greater then 0
for (var EnquiryType in json.enquiryTypes) { //go through each EnquiryType in JSON
$("<option />", {
val: json.enquiryTypes[EnquiryType].EnquiryId, //mapping
text: json.enquiryTypes[EnquiryType].Enquiryname //mapping
}).appendTo(targetDropdown); //add to drop down
};
}
targetDropdown.change();
}
});
});
Try this:
$(document).ready(function() {
$('#profession').trigger('change');
});

Categories