Create option tag via Javascript issue - javascript

i am using AJAX to bring some data from my DB , after the AJAX success i am trying to create <option> tag via JavaScript but it seems it doesnt work and nothing happen at the DOM and i cant figure why ?
$("#clientCombo").on("change", function () {
$.ajax({
url: "/Account/GetBrands",
data: { clientID: $("#clientCombo").val() },
dataType: 'json',
success: function (result) {
if (result.error == undefined) {
var brandList = result;
var brandCombo = $('#brandCombo');
var brandOption = $("<option value=\"none\">"+"someString+"+"</option>");
brandCombo.html(brandOption);
for (var i = 0; i < brandList.length; i++) {
brandCombo+=("<option value=\"" + brandList[i].brandID + ">" + brandList[i].brandName + "</option>");
}
}
else {
$("#brandCombo").html("<option value=\"none\">" + "choose+" + "</option>");
}
}
});
});
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.0.min.js"></script>
<script src="https://cdn.quilljs.com/1.0.0/quill.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<div class="input-group">
<label class="inputLabel">name</label>
<select id="clientCombo" class="selectpicker">
<option value="none">choose</option>
#foreach (var clientItem in Model.clientList)
{
<option value="#clientItem.ID">#clientItem.ClientName</option>
}
</select>
</div>
<div class="input-group">
<label class="inputLabel">brand</label>
<select id="brandCombo" name="MotagNumber" class="selectpicker">
</select>
</div>
i am using this scripts :
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.0.min.js"></script>
<script src="https://cdn.quilljs.com/1.0.0/quill.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>

You are not using correct variable brandOption while creating options string and use .html() after the loop.
var brandOption = $("<option value=\"none\">"+"someString+"+"</option>");
for (var i = 0; i < brandList.length; i++) {
brandOption+=("<option value=\"" + brandList[i].brandID + ">" + brandList[i].brandName + "</option>");
}
brandCombo.html(brandOption); //Once options string is completely created
instead of
var brandOption = $("<option value=\"none\">"+"someString+"+"</option>");
brandCombo.html(brandOption);
for (var i = 0; i < brandList.length; i++) {
brandCombo+=("<option value=\"" + brandList[i].brandID + ">" + brandList[i].brandName + "</option>");
}

check your for loop
brandOption+="<option value=\"" + brandList[i].brandID + "\">" + brandList[i].brandName + "</option>";
use this problem will be solved

Instead of string concatenation, you should use Jquery built-in function .append() - Insert content, specified by the parameter, to the end of each element in the set of matched elements.
$('#brandCombo').append('<option value='+brandList[i].brandID+'>'+brandList[i].brandName+'</option>')
And you can also use .empty() to clear all <option> tags from the dropdown. like below
$('#brandCombo').empty()

try below code
$(document).on("change","#clientCombo", function () {
$.ajax({
url: "/Account/GetBrands",
data: { clientID: $("#clientCombo").val() },
dataType: 'json',
success: function (result) {
if (result.error == undefined) {
var brandList = result;
var brandCombo= $('<select>');
for (var i=0; i<brandList.length ;i++)
{
brandCombo.append( $('<option><option>').val(brandList[i].brandID).html(brandList[i].brandName) );
}
$('#brandCombo').append(brandCombo.html());
}
else {
$("#brandCombo").html("<option value=\"none\">choose</option>");
}
});
});

Related

Display value in dropdown based on first dropdown

I have a working form here which populating dropdown from the database, i want to do here is display the value of 2nd dropdown based on the selected value on the 1st dropdown, but how i'm gonna do it. My Class will only display on the 2nd drowpdown if error is selected which the 1st dropdown
//my screenshot, my only sample data
enter image description here
Backend code:
public JsonResult GetErrorCategory()
{
List<ErrorCategory> error = errorDataAccessLayer.GetAllError(Action);
return Json(error.Select(x => new
{
errorCode = x.ErrorCode,
errorDescription = x.ErrorDescription
}).ToList(), JsonRequestBehavior.AllowGet);
}
public JsonResult GetClassCategory()
{
List<ErrorClass> error = errorDataAccessLayer.GetAllClass(Action);
return Json(error.Select(x => new
{
classCode = x.ClassCode,
classDescription = x.ClassDescription
}).ToList(), JsonRequestBehavior.AllowGet);
}
View:
<form id="ticket_form" method="post" enctype="multipart/form-data">
<div class="row">
<div class="form-group col-md-4">
<label><strong>Error Type</strong></label>
<select name="ErrorType" id="ErrorDropdown" class="form-control ErrorType" >
</select>
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label><strong>Class Type</strong></label>
<select name="ClassType" id="ClassDropdown" class="form-control ClassType" >
</select>
</div>
</div>
<div class="form-group">
<input type="submit" id="addTicket" value="Create" class="btn btn-md btn-outline-secondary" style="margin:auto;display:block;" />
</div>
</form>
Javascript code:
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/Ticket/GetErrorCategory",
data: "{}",
success: function (data) {
var s = 'option value="-1">Please Select Error Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].errorDescription + '">' + data[i].errorDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ErrorDropdown").html(s);
}
});
$.ajax({
type: "POST",
url: "/Ticket/GetClassCategory",
data: "{}",
success: function (data) {
var s = 'option value="-1">Please Select Class Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].classDescription + '">' + data[i].classDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ClassDropdown").html(s);
}
});
});
</script>
First, in script section you need split functions like as following. You see I added code parameter to the second GetClassCategory method:
function GetErrorCategory() {
$.ajax({
type: "POST",
url: "/Ticket/GetErrorCategory",
data: "{}",
success: function (data) {
var s = 'option value="-1">Please Select Error Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].errorDescription + '">' + data[i].errorDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ErrorDropdown").html(s);
// This line applies onchange event for errorcategory dropdown
ApplyErrorCategoryDropDownOnChange();
}
}
}
function GetClassCategory(code) {
$.ajax({
type: "POST",
url: "/Ticket/GetClassCategory",
data: JSON.stringify({ code: code }),
success: function (data) {
var s = 'option value="-1">Please Select Class Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].classDescription + '">' + data[i].classDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ClassDropdown").html(s);
}
});
}
Second, you need handle onchange() event, because when another item of the first dropwdown selected then you need get it's value.
function ApplyErrorCategoryDropDownOnChange() {
$("#ErrorDropdown").change(function (data) {
GetClassCategory(this.value)
});
}
Third, you must call GetErrorCategory() method from document ready function.
$(function () {
GetErrorCategory();
});
Fourth, you need add code parameter in the backend section, and apply this parameter to your db query:
public JsonResult GetClassCategory(string code) // I added parameter
{
List < ErrorClass > error = errorDataAccessLayer.GetAllClass(Action);
return Json(
error
.Where(x => x.ClassCode = code) // I added this section
.Select(x => new
{
classCode = x.ClassCode,
classDescription = x.ClassDescription
}).ToList(), JsonRequestBehavior.AllowGet);
}
You have to change your code in your second ajax call, i mean it should be some dependent conditional to the first dropdown, For that you just need to get the value of the first dropdown to the second dropdown ajax call while it is selected. Just i mention below :
var error=document.getElementById("ErrorDropdown").value;
$.ajax({
type: "POST",
url: "/Ticket/GetClassCategory",
data: "{error:error}",
success: function (data) {
var s = 'option value="-1">Please Select Class Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].classDescription + '">' + data[i].classDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ClassDropdown").html(s);
}
});
Here i have the value of the first dropdown in variable named as error and i have passed it through the ajax call and use it in my database query with where clause.

str_replace inside js from Ajax call data

i want to replacement character from data loop ajax (data[i]) to some values,
i have this js
<script type="text/javascript">
$(document).ready(function() {
$('select[name="parameter"]').on('change', function() {
var idpar = $(this).val();
var subdir = $('input[name="subdirid"]').val();
var year = $('input[name="added_year"]').val();
var i = 0;
if (idpar != '') {
$.ajax({
url: "{{URL::to('myform/myformColaborate')}}/" + idpar + "/" + subdir + "/" + year,
type: "GET",
dataType: "json",
success: function (data) {
$.each(data, function (key, city2) {
$('select[name="type2"]').empty();
$('select[name="type2"]').append(
'<option disabled selected>Select Request Colaborate</option>'
);
for (var i = 0; i < data.length; i++) {
$('select[name="type2"]').append(
'<option value="'+ data[i] +'">Request Colaborate with '+ data[i] +'</option>'
);
}
});
}
});
}
});
});
</script>
and the controller
public function myformColaborate($idpar, $subdir, $year) {
$cities = DB::table("pra_kpis")
->where('subdir_colaborate','like','%'.$subdir.'%')
->where('added_year',$year)
->where('kpi_parameters_id',$idpar)
->distinct()
->pluck("subdirs_id");
return response()->json($cities, 200);
}
for example , i have script replacement outside js like this, how to define it inside js
<?php
$roles = DB::table('pra_kpis')->where('id','=',$l->id)->pluck('subdir_colaborate');
$dir2 = DB::table('subdirs')->select('name')->pluck('name');
$iddir = DB::table('subdirs')->select('id')->pluck('id');
?>
#foreach($roles as $drop)
{{$drop = str_replace($iddir, $dir2, $drop)}}
#endforeach
Try this:
Do it from front-end only,
Use data[i].replace('search string', 'replace string');

How to get data from webservice in jquery?

I have a web service with link: http://41.128.183.109:9090/api/data/getalllocations
I recived this data in dropdown using jquery .this data contains 2 objects LocationName and LocID. I want to display an alert with LocID in dropdown change function in jQuery. Here is my code:
$(document).ready(function () {
$.ajax({
type: 'Get',
url: 'http://41.128.183.109:9090/api/data/getalllocations',
success: function (data) {
var SubDropdown = $("#main");
for (var i = 0; i < data.length; i++) {
SubDropdown.append('<option value?' + i + '?="">' + data[i].LocationName + '</option>');
}
}
});
});
$("#countries").change(function () {
alert();
});
Here is my HTML code :
<select tabindex="-1" class="select2_group form-control" style="display: normal; width: 290px;" name="countries" id="countries">
<optgroup label="Select Your City" id="main"></optgroup>
</select>
please try following
$(document).ready(function () {
$.ajax({
type: 'Get',
url: 'http://41.128.183.109:9090/api/data/getalllocations',
success: function (data) {
var SubDropdown = $("#main");
for (var i = 0; i < data.length; i++) {
SubDropdown.append('<option value="' + data[i].LocID + '">' + data[i].LocationName + '</option>');
}
}
});
$("#countries").change(function () {
alert($("#countries").val());
});
});

How can use multiple javascript?

Hello everyone I'm trying to run multiple javascripts. My first javascript is which has change function working fine but second one does not work. So how can i run multiple javascript code? Here is my code :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#main').on('change', '.select-box', function () {
if ($(".select-box option[value='3']").attr('selected')) {
$('#demo').html("<select class='select-box'><option value='4'>a</option><option value='5'>b</option></select>");
}
if ($(this).val() == 5) {
document.getElementById("demo").innerHTML = "Woo";
}
});
});
</script>
<script>
var x = "", i;
for (i = 0;i < 3;i++) {
x = x + "<option value='" + i + "'> " + i + "</option>";
}
document.getElementById("demo2").innerHTML = "<select>" + x + "</select>";
</script>
</head>
<body>
<div id="main">
<select class="select-box">
<option>Select an option</option>
<option value="1">no alert</option>
<option value="2">no alert too</option>
<option value="3">alert</option>
</select>
<p>
<br/>
</p>
<div id="demo"></div>
</div>
<p id="demo2"></p>
</body>
</html>
You can try something like this if you want to use jQuery and some other javascript libs
<script type="text/javascript" src="other_lib.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$.noConflict();
jQuery(document).ready(function($) {
// Code that uses jQuery's $ can follow here.
});
// Code that uses other library's $ can follow here.
</script>
In your code there is additional the type="text/javascript" missing in the script tag. So it schould look like this:
<script type="text/javascript">
var x="",i;
for(i=0;i<3;i++)
{
x=x + "<option value='"+i+"'> " + i + "</option>";
}
document.getElementById("demo2").innerHTML="<select>"+x+"</select>";
</script>
This script:
<script>
var x="",i;
for(i=0;i<3;i++)
{
x=x + "<option value='"+i+"'> " + i + "</option>";
}
document.getElementById("demo2").innerHTML="<select>"+x+"</select>";
</script>
Tries to get the element demo2 before it exists. Move the script to somewhere after demo2, maybe right before </body>.
Or, alternatively, put that last part in a ready handler like your first script:
<script>
var x="",i;
for(i=0;i<3;i++)
{
x=x + "<option value='"+i+"'> " + i + "</option>";
}
$(document).ready(function() {
document.getElementById("demo2").innerHTML="<select>"+x+"</select>";
});
</script>
And here's how I'd do it, by the way:
var demo2 = document.getElementById('demo2');
for(var i = 0; i < 3; i++) {
var item = document.createElement('option');
item.value = i;
item.appendChild(document.createTextNode(i.toString()));
demo.appendChild(item);
}

Rss feed items get pulled in several times

I'm having a problem pulling in a RSS feed in my phonegap application. The code works and the feed gets pulled in correctly, but each item is displayed 3 times. What am I doing wrong here?
function getEvents() {
showLoading();
$.getFeed({
url: 'http://thisismyfeedurl.com',
success: function(feed) {
var html = '';
for(var i = 0; i < feed.items.length; i++) {
var item = feed.items[i];
html += '<li><p><a class="title" href="#">' + item.title + '</a>' + item.description + '</p></li>';
$('#eventscount').text(i);
}
$('#eventsfeed').append(html);
hideLoading();
$('object').show();
}
});
};
I tested your code. It works fine. Ps, comics.xml is http://www.reddit.com/r/comics.xml
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://raw.github.com/jfhovinne/jFeed/master/build/dist/jquery.jfeed.js"></script>
<div id="eventscount"></div>
<div id="eventsfeed"></div>
<script type="text/javascript">
$(document).ready(function () {
$.getFeed({
url: 'comics.xml',
success: function(feed) {
var html = '';
for(var i = 0; i < feed.items.length; i++) {
var item = feed.items[i];
html += '<li><p><a class="title" href="#">' + item.title + '</a>' + item.description + '</p></li>';
$('#eventscount').text(i);
}
$('#eventsfeed').append(html);
}
});
});
</script>
24
Money in Sight!submitted by imasif [link] [11 comments]
From my sketchbook: Evolutionary stages of Redditsubmitted by
Schaafwond [link] [55 comments]
Basically, every sports column I read on Monday...submitted by milk4dh
[link] [21 comments]
(snip)

Categories

Resources