For loop inside a each function, add option selected - javascript

Code: Fetch JSON and create cart contents. Create a list of each products info, and have a form required for each product to update qty
$.ajax({
url: "myurl",
type: 'POST',
dataType: "json"
}).done(function(response){
$.each(response,function(k,v){
//UL this products info list was here
var otions = '';
for( i=1; i<20; i++ ){
options += '<option value="'+i+'">'+i+'</option>';
}
var form = '<form action="myurl" method="post" accept-charset="utf-8"><label for="products_qty">Quantity</label>'
+'<select name="products_qty>'
+options
+'</select>'
+'<input type="hidden" name="row_id" value="17e62166fc8586dfa4d1bc0e1742c08b" />'
+'<input type="submit" name="submit_item" value="Update" /></form>';
$('#formWrapper').append(form);
});
});
The code runs well. In the for loop I need to add selected=selected to a particular option tag.How and where will this be added.
Can a if statement be achieved inside for loop?
var otions = '';
for( i=1; i<20; i++ )
{
if(i=7)
{
var select = 'selected="selected"';
}
options += '<option value="'+i+'" '+select+'>'+i+'</option>';
}
Ive seen the following link and tried adding their stuff just before my apped, and no luck.
set option "selected" attribute from dynamic created option

Try this changes,
var otions = '';
for( i=1; i<20; i++ ){
if(i==7){
options += '<option value="'+i+'" selected="selected">'+i+'</option>';
}
else
options += '<option value="'+i+'" +select+>'+i+'</option>';
}

The problem with your code:
var otions = '';
for( i=1; i<20; i++ )
{
if(i=7)
{
var select = 'selected="selected"';
}
options += '<option value="'+i+'" '+select+'>'+i+'</option>';
}
... is that select only exists inside the if statement, because that's where you're defining it.
So:
var otions = '';
for( i=1; i<20; i++ )
{
var select;
if(i=7)
{
select = 'selected="selected"';
}
else
{
select = "";
}
options += '<option value="'+i+'" '+select+'>'+i+'</option>';
}

Maybe this is what you want:
var select = i === 7 ? " selected='selected'" : '';
options += "<option value='"+i+"'"+select+'>'+i+'</option>';

Related

Change Ajax Post parameters & returned HTML based on alternating dependant dropdowns

I have 3 dropdowns containing values that are populated on page load
<select class='form-control' id='make' placeholder='Make:'>
<select class='form-control' id='model' placeholder='Model:'>
<select class='form-control' id='version' placeholder='Version:'>
I have a function that updates the values in the 'other' dropdowns that aren't clicked, based on the value of the dropdown that is clicked - but I have this function repeated 3 times, for each dropdown
$('#model').change(function(){
let selectedModel = $(this).val();
$.ajax({
url: 'php/dropdown.php',
type: 'POST',
data: {model: selectedModel},
success:function(data)
{ $('#make').html('');
$('#version').html('');
let makeJSON = JSON.parse(data)[0];
let versionJSON = JSON.parse(data)[2];
for (let i = 0; i < makeJSON.length; i++) {
if (makeJSON[i].mMake!= '' && makeJSON[i].mMake!= null) {
$('#make').html($('#make').html() + '<option value="' + makeJSON[i].mMake + '">' + makeJSON[i].mMake + '</option>');
}
}
for (let i = 0; i < versionJSON.length; i++) {
if (versionJSON[i].mVersion != '' && versionJSON[i].mVersion != null) {
$('#version').html($('#version').html() + '<option value="' + versionJSON[i].mVersion + '">' + versionJSON[i].mVersion + '</option>');
}
}
}
});
});
And the PHP looks something like this:
$model = $_REQUEST['model'];
$sqlupdateModel = "SELECT DISTINCT mMake, mVersion FROM Cars WHERE mModel = '$model';
$stmtModel = sqlsrv_query( $conn, $sqlupdateModel);
if( $stmtModel === false)
{
die( print_r( sqlsrv_errors(), true));
}
$updateModel = [];
while( $row = sqlsrv_fetch_array( $stmtModel, SQLSRV_FETCH_ASSOC)){
$updateModel[] = $row;
}
echo json_encode(array($updateMake, $updateModel, $updateVersion));
...and this all works fine,
Basically, I'm looking for a simpler solution for reusing the function (both JS & PHP) instead of rewriting it 3 times!
In terms of what I have attempted,
$('#make, #model, #version').change(function(){
let columnValue = $(this).val();
.......
data: {model: columnValue},
success:function(data)
{$(this).html(''); //this doesn't work obviously!
After this I'm snookered
This one should work for JS side, you will have to check mapping function for response
$('#make, #model, #version').change(function(ev){
let selected = $(this).val();
let id = ev.target.id;
let data = {};
data[id] = selected;
$.ajax({
url: 'php/dropdown.php',
type: 'POST',
data: data,
success:function(data)
{
let options = ['make', 'model', 'version']
const response = {
make: JSON.parse(data[0].map(make => make.mMake)),
model: JSON.parse(data[1].map(make => make.mModel)),
version: JSON.parse(data[2].map(make => make.mVersion))
}
options.filter(option => option !== id).forEach(option => setDropdown(option, response[option]));
}
});
});
function setDropdown(id, data) {
const id = `#${id}`
$(id).html('');
for (let i = 0; i < data.length; i++) {
if (data[i] != '' && data[i] != null) {
$(id).html($(id).html() + '<option value="' + data[i] + '">' + data[i] + '</option>');
}
}
}

Boostrap select : class selectpicker doesn't appear

I send a ajax request to have the different option for my select tag.
$.ajax({
type: 'GET',
url: '/first_line_benefits',
data: { tablename: tablename },
success: function(data) {
var dataArray = data[0];
var ret = "";
for (var j = 1; j < dataArray.length; j++) {
ret += "<div class=\"filter_button col-md-4\">";
ret += "<select class=\"selectpicker\" multiple><option value='0' selected>Nothing selected</option>";
for (var i = 0; i < dataArray[j].length; i++)
{
ret += "<option>"+ dataArray[j][i] + "</option>";
}
ret += "</select></div>";
}
$('#filter').html(ret);
}
});
The problem is : nothing appears on the page.
But if I remove the selectpicker class, a basic multiple select appears.
I tried to instance the selectpicker on the JS
$('.selectpicker').selectpicker();
And I tried to show the selectpicker with the method "show"
$('.selectpicker').selectpicker('show');
EDIT :
Screenshot of the homepage (selectpicker class is here but nothing appears on the webpage
Browser console log

How to dynamically Add and Remove multiple <tr> with input fields

What i m trying to do is when the user type number quantity automatically jquery must create that number of with inputs.
so i used this code to generate
$( "#cont_qty" ).change(function()
{
var cont_qty = this.value;
for(var i=1 ; cont_qty>i; i++)
{
itemCount++;
// dynamically create rows in the table
var auto_tr = '<tr id="tr'+itemCount+'"><td><input class="input-medium" type="text" id="cont_no'+itemCount+'" name="cont_no'+itemCount+'" value=""></td></tr>';
$("#munna").append(auto_tr)
}
});
If the user type 5 then it creates 4 now if the user change the value and type 7 then have to remove the previous created those 4 and then have to create 6
now i dont know how to remove
Empty before looping, and start at zero
$( "#cont_qty" ).change(function() {
var cont_qty = this.value;
$("#munna").empty();
for(var i=0 ; cont_qty>i; i++) {
itemCount++;
var auto_tr = '<tr id="tr'+itemCount+'"><td><input class="input-medium" type="text" id="cont_no'+itemCount+'" name="cont_no'+itemCount+'" value=""></td></tr>';
$("#munna").append(auto_tr)
}
});
use Html() not append()
$("#cont_qty").change(function () {
var cont_qty = this.value;
var html = "";
for (var i = 1; cont_qty >= i; i++) {
itemCount++;
// dynamically create rows in the table
html += '<tr id="tr' + itemCount + '"><td><input class="input-medium" type="text" id="cont_no' + itemCount + '" name="cont_no' + itemCount + '" value=""></td></tr>';
}
$("#munna").html(html);
});
$( "#cont_qty" ).change(function()
{
var cont_qty = this.value;
var html = '';
for(var i=1 ; cont_qty>i; i++)
{
itemCount++;
// dynamically create rows in the table
html += '<tr id="tr'+itemCount+'"><td><input class="input-medium" type="text" id="cont_no'+itemCount+'" name="cont_no'+itemCount+'" value=""></td></tr>';
}
$("#munna").html(html);
});
To prevent it from creating one less than you want, change this:
for(var i=1 ; cont_qty>i; i++)
to this:
for(var i=1 ; i<=cont_qty; i++)
And, has already been stated, as you want to reset the amount of fields everytime you change the number, change $("#munna").append(html); to $("#munna").html(html);
$( "#cont_qty" ).change(function()
{
var cont_qty = this.value;
for(var i=1 ; cont_qty>i; i++)
{
itemCount++;
html += '<tr id="tr'+itemCount+'"><td><input class="input-medium" type="text" id="cont_no'+itemCount+'" name="cont_no'+itemCount+'" value=""></td></tr>';
}
$("#munna").html(html)
});
Beside of use 'append' the html div, .html can reload the div content.
change the whole html content of #munna with html()
$( "#cont_qty" ).change(function()
{
var cont_qty = this.value;
for(var i=1 ; cont_qty>i; i++)
{
itemCount++;
// dynamically create rows in the table
var auto_tr += '<tr id="tr'+itemCount+'"><td><input class="input-medium" type="text" id="cont_no'+itemCount+'" name="cont_no'+itemCount+'" value=""></td></tr>';
}
$("#munna").html(auto_tr)
});
You have to use .html() instead of .append() outside of your loop.
$("#munna").html(html);
Instead of
$("#munna").append(html);

Jquery append html weird behavior

i have the following ajax:
$.ajax({
type: 'POST',
url: myBaseUrl + 'Products/ajax_get_subcategories',
dataType: 'json',
data: {
id: id
},
success: function (data) {
var length = data.length;
var div_subcategory = $('#subcategory');
div_subcategory.html('');
div_subcategory.append(
"<select id='subcategory' name='data[Product][subcategory_id]'>"
);
for (var i = 0; i < length; i++) {
var id = data[i]['Subcategory']['id'];
var name = data[i]['Subcategory']['name'];
$('#subcategory').append(
"<option value=''+id>" + name + "</option>"
);
}
div_subcategory.append("</select>");
}
});
Now as you can see it appends a select into a div block.
But! there is a catch here is the output of the HTML after the ajax has been called:
div id="subcategory" class="subcategory">
<select id="subcategory" name="data[Product][subcategory_id]"></select>
<option +id="" value="">Telte</option>
<option +id="" value="">Toilet</option>
<option +id="" value="">Service</option>
<option +id="" value="">Borde</option>
<option +id="" value="">Stole</option>
<option +id="" value="">Lyd og lys</option>
</div>
As you can see it closes the select tag before adding the options.
Can anyone tell me why this is happening?
When you write:
div_subcategory.append("<select id='subcategory' name='data[Product][subcategory_id]'>");
jQuery will insert
<select id='subcategory' name='data[Product][subcategory_id]'></select>
And becasue div_subcategory will have the same id as the select you will be matching the div instead.
Instead I would write this by creating the html in a string and injecting it all at once.
var html += "<select id='subcategorysel' name='data[Product][subcategory_id]'>";
for (var i = 0; i < length; i++) {
var id = data[i]['Subcategory']['id'];
var name = data[i]['Subcategory']['name'];
html += "<option value=''+id>" + name + "</option>";
}
html += "</select>";
div_subcategory.append(html);
This snippet updates your code to use different ids and appends the html all in one go which should be quicker.
Try
change your success code
success: function (data) {
var length = data.length;
var div_subcategory = $('#subcategory');
div_subcategory.html('');
var select_append = "<select id='subcategory' name='data[Product][subcategory_id]'>";
for (var i = 0; i < length; i++) {
var id = data[i]['Subcategory']['id'];
var name = data[i]['Subcategory']['name'];
select_append += "<option value=''" + id + ">" + name + "</option>";
}
select_append += "</select>"
div_subcategory.append(select_append);
}
create a variable select_append and concatenate all your code in that and append that variable in the end.
Try
$(div_subcategory).find('select').append(...)
when you write this syntex
div_subcategory.append(
"<select id='subcategory' name='data[Product][subcategory_id]'>"
);
DOM automatically detects an HTML element like this
<select id='subcategory' name='xxx'></select>
and then you are appending other option elements after this
so solution is first make a string of an HTML and then append like
var html = "<select id='subcategory' name='data[Product][subcategory_id]'>";
for (var i = 0; i < length; i++) {
var id = data[i]['Subcategory']['id'];
var name = data[i]['Subcategory']['name'];
html += "<option value='' + id>" + name + "</option>";
}
div_subcategory.append(html);

Creating a loop that populates a select tag

function buildOrder(data) {
var $fragment;
$fragment = $('<div/>');
for (var i = 0; i < data.length; i++) {
$fragment.append('<div class="row-container"><div class="row cupcake-row">' + data[i].name + '</div><div class="clear"></div></div>');
}
$('#review-section').append($fragment);
}
I essentially want to add a tag with 50 options being dynamically created using a for loop. But I'm not sure what the syntax would be to add it to the <div class="row-container"/> I know in php I would just throw the loop in the middle and echo the options, however that doesnt work in javascript.
EDIT:
It would look like this:
$fragment.append('<div class="row-container"><div class="row cupcake-row">' + data[i].name + '</div><select><option value="1">1</option> etc...</select><div class="clear"></div></div>');
You could pass a function to .append and do your loop there:
$("<div>").append(function() {
var $select = $("<select>");
for(var i = 1; i <= 50; i++) {
$("<option>").text(i).val(i).appendTo($select);
}
return $select;
});
// returns a jQuery object with one div element (with children):
// <div>
// <select>
// <option value="1">1</option>
// ...
// </select>
// </div>
Mixed into your code it would be along the lines of:
var $fragment = $("<div>");
for (var i = 0; i < data.length; i++) {
var $container = $("<div>").addClass("row-container")
.appendTo($fragment);
$("<div>").addClass("row cupcake-row")
.text(data[i].name)
.appendTo($container);
$("<div>").append(function() {
var $select = $("<select>");
for(var i = 1; i <= 50; i++) {
$("<option>").text(i).val(i).appendTo($select);
}
return $select;
}).appendTo($container);
$("<div>").addClass("clear")
.appendTo($container);
}
$("#review-section").append($fragment);
Try something like this
function buildOrder(data) {
var $fragment = $('<div></div>');
var options = [];
for (var i = 0; i < data.length; i++) {
options.push('<div class="row-container"><div class="row cupcake-row">' + data[i].name + '</div><div class="clear"></div></div>');
}
$fragment.html(options.join("\n"));
$('#review-section').append($fragment);
}
According to your posted code:
function buildOrder(data) {
var $fragment;
$fragment = '<div><div class="row-container">';
for (var i = 0; i < data.length; i++) {
$fragment += '<div class="row cupcake-row">' + data[i].name + '</div><div class="clear"></div>';
}
$fragment += '</div></div>';
$('#review-section').append($fragment);
}
But in your posted code doesn't match with your post title, where you mentioned about select tag and in your code you're trying with div.
If you want to create a select, then something like:
function buildOrder(data) {
var $fragment;
$fragment = '<div class="row-container"><select>'; // taking select within your div
for (var i = 0; i < data.length; i++) {
// adding options to select
$fragment += '<option value="'+ data[i].name +'">' + data[i].name + '</option>';
}
$fragment += '</select></div>'; // end select and div
$('#review-section').append($fragment);
}

Categories

Resources