I am trying to populate a dropdown menu on behalf of the value of an other dropdown. the problem here is that the function i am trying to call in select tag's onChange event is not being compiled. and an error is appearing in console.enter code here.
HTML:
<select name="street_id" id="street_id" onchange="get_data(this)" class="input-xlarge">
</select>
Jquery:
<script type="text/javascript">
function get_data()
{
$('#client_list').empty()
var dropDown = document.getElementById("street_id");
var street_id = dropDown.options[dropDown.selectedIndex].value;
$.ajax({
type: "GET",
url: "http://localhost:7777//index.php/admin/get_one_street_client/" + street_id,
data: { 'street_id': street_id },
success: function(data){
// Parse the returned json data
var opts = $.parseJSON(data);
// Use jQuery's each to iterate over the opts value
$.each(opts, function(i,d) {
console.log(d.client_name);
// You will need to alter the below to get the right values from your json object. Guessing that d.id / d.modelName are columns in your carModels data
<?print "var value == '$balance_data[0]->client_id'";
//$selected = 'selected';
?>
$('#client_list').append('<option value="' + d.client_id + ' ">' + d.client_name + '</option>');
});
}
});
}
</script>
Error:
insert_balance:180
Uncaught ReferenceError: get_data is not definedonchange #
insert_balance:180
i have already added the jquery library address on top.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Clearly, you should not put that php inside the success callback of the AJAX response. I can't imagine what good this could do. Just erase those lines.
I don't know what that php generates, but it looks like it generates a syntax error in function get_data().
This means the whole script (within the script tags) does not get compiled.
Also, it looks like that line of code isn't doing anything, even if it didn't cause problems
var value == 5 ; no idea why this code is present
Related
I have a page with a hidden drop-down box that appears when a checkbox is ticked via a JavaScript inner.HTML = command. As I'm aware I wouldn't be able to populate this from a document.onload function, I've got a <div>, that I'll be setting to style="display:none" when I have this working, where I have a drop-down box in for the options to be populated to, however I'm getting the error message 'Unable to set property 'innerHTML' of undefined or null reference' when attempting to do this. Is a <select> tag not able to have an ID or innerHTML value given to it?
Code is below:
var systemOptions = [];
var system = document.getElementById("systemstemp");
document.onload = getSystems();
function getSystems() {
$.ajax({
url: ".../_api/web/lists/getbytitle('Application List')/items?$select=Title",
type: "GET",
headers: {"accept": "application/json;odata=verbose"},
success: function (data) {
systemOptions = data.d.results;
for (var obj in systemOptions) {
system.innerHTML = "<option value='" + systemOptions[obj].Title + "'>" + systemOptions[obj].Title + "</option>";
}
}
});
}
<p><select id="systemstemp"></select></p>
systemOptions = [
{Title: "Call Platform"},
{Title: "CRM"},
{Title: "Email"},
{Title: "Monitoring"},
]
The problem is that when you do:
document.onload = getSystems();
you're actually calling getSystems function immediately and not when document.onload fires. In order to run getSystems when onload triggers, set the function without parenthesis:
document.onload = getSystems;
or assign the function directly to the document.onload:
document.onload = function() {
$.ajax({...});
}
EDIT
You should also use DOM API to create the select options like in this Q/A:
Adding options to select with javascript
I’ve already tried to get the element by id, however, the html does not include it. As shown below, this is the script for the drop down that I am trying to change automatically. It will change the name with
appIE.Document.getElementById("supervisor").Value = "Sup_name"
However, it doesn’t fire the event that generates a list of people.
The top of the form also includes <form id='filterform' action="javascript:void(0);">
The JavaScript containing the function I need to call is below.
<script type="text/javascript">
$(function() {
$('#supervisor').change(function() {
document.getElementById('results').innerHTML = '<img src="/img/busy.gif" />';
var str = $('#filterform').serializeArray();
$.ajax({
url: 'ajax.php?p=agentrosters&mode=1&field=supervisor',
type: 'POST',
data: str,
success: function(j) {
//alert(j);
document.getElementById('results').innerHTML = j;
document.getElementById('lastsearch').value = 'supervisor';
resetscript('supervisor');
},
failure: function() {
document.getElementById('results').innerHTML = 'There has been an error, please try again';
resetscript('null');
}
})
})
})
</script>
Any Ideas on how I can get this to work?
If the element is part of a form you may to submit the form, alternatively you can use the onchange event on the element itself. So you may want to change appIE.Document.getElementById("supervisor").Value = "Sup_name" to
With appIE.document.getElementById("supervisor")
.Value = "Sup_name"
.onchange
End with
And if it is part of a form change the ".onchange" to
".parentElement.Submit"
This worked for me.
In trying to cleanup my code base, I moved all of my javascript from script tags to their own javascript file. After doing that, all of my ajax calls are failing.
Here's the javascript, this is EXACTLY how it was in the *.cshtml file, excluding the script tags:
$(function () {
$("#weightList").change(function () {
var weight = $("#weightList").val();
var conference = $("#conference").val();
$("#wrestlerAList").prop('disabled', true);
$("#wrestlerBList").prop('disabled', true);
$.ajax({
url: '#Url.Action("GetByWeight", "Wrestler")',
data: {
weight: weight
},
type: 'POST',
success: function (data) {
var wrestlers = "<option></option>";
$.each(data, function (i, wrestler) {
wrestlers += "<option value='" + wrestler.Value + "'>" + wrestler.Text + "</option>";
});
$("#wrestlerAList").html(wrestlers);
$("#wrestlerBList").html(wrestlers);
$("#wrestlerAList").prop('disabled', false);
$("#wrestlerBList").prop('disabled', false);
},
error: function (error) {
alert("An error occurred retrieving the wrestlers for this weight.");
}
});
});
});
I've tried removing the "$(function () {...});" but that didn't work. Is there other syntax required when the javascript is not directly on the cshtml page?
Edit: I'm loading my javascript file at the very end of the cshtml file, right before the closing tag.
Also, I'm getting a 404 back. If the code stayed the same, why would it now be getting a 404?
url: '#Url.Action("GetByWeight", "Wrestler")',
that line needs to be rendered on a cshtml page. it doesnt get processed in a .js file.
The problem is with the way you are setting the ajax url
url: '#Url.Action("GetByWeight", "Wrestler")'
The ASP.NET MVC tag helper #Url.Action() will not work inside a .js file.
You could place the url in a hidden form field and read it from there.
Place this somewhere in the .cshtml preferably outside of any forms so it is not posted back in the form for any reason.
#Html.Hidden("ServiceUrl", Url.Action("GetByWeight", "Wrestler"))
Then use the code below to set the jQuery ajax url
url: $('#ServiceUrl').val(),
What am I missing? I've added the get element by Id and I'm definitely getting a response back, I checked using firebug and the response is correct. But I can't figure out why it won't populate my div area.
<script>
$(document).ready(function () {
$("#cmdSend").click(function () {
// Get he content from the input box
var mydata = document.getElementById("cmdInput").value;
$.ajax({
type: "POST",
url: "/Terminal/processCommand",
data: { cmd: mydata }, // pass the data to the method in the Terminal Contoller
success: function (data) {
//alert(data);
// we need to update the elements on the page
document.getElementById("terminal").value = document.getElementById("terminal").value + mydata;
document.getElementById("terminal").value = document.getElementById("terminal").value + data;
},
error: function (e) { alert(e); }
})
});
});
</script>
And the Div I want the response to be put in:
<div class="terminal" style="overflow:scroll">
<br>
</div>
First, you are calling document.getElementById(), but your div does not have an ID of terminal, it has a class called terminal.
Second, you are using jQuery but then switch back to classic JavaScript. You could update your code to the following:
success: function (data) {
//alert(data);
// we need to update the elements on the page
var existingHtml = $(".terminal").html();
$(".terminal").html(existingHtml + mydata + data);
}
Note that the $(".SomeName") selector is for selecting by class and $("#SomeName") is to select by id.
Edit and Note
If this terminal div could start to get a lot of data inside of it, you may look at using the .append() function in jQuery to prevent having to make a copy of the HTML and overwrite the HTML each time a request is made. The update would be something similar to the following (its a little shorter and should be more efficient as well)
success: function (data) {
//alert(data);
// we need to update the elements on the pag
$(".terminal").append(mydata + data);
}
If you want to get your element by id, add an id to the div:
<div id=terminal class="terminal" style="overflow:scroll">
<br>
</div>
If you want to change the contend of div not using jquery, you should use innerHTML instead of value.
document.getElementById("divID").innerHTML = document.getElementById("divID").innerHTML + data
I have a page that I load a select dropdown box but I want to have javascript code toggle this list to a different set of choices.
I have the code that clears and repopulates a select list box in javascript
function UpdateDropdown(list, dropdownSelector) {
var options = '';
$.each(list, function (index, value) {
if (value.Text == null) {
value.Text = '';
}
if (value.Value == null) {
value.Value = '0';
}
options += '<option value="' + value.Value + '">' + value.Text + '</option>';
});
$(dropdownSelector).html(options);
}
so that is not the issue but my question is How can i store an array locally from my view Model to lookup later from javascript? Should i store it in a hidden select box? is there a recommended practice here?
The easiest and cleanest solution is to just write some json to your view, stored in a variable that you then access inside your UpdateDropdown function. In your view:
<script type="text/javascript">
var globalData = #Html.Raw(Json.Encode(Model.MyArray));
</script>
The exact method you use to output json will differ depending on the version of ASP.NET MVC you're using, but that should put you on the right track.
And general javascript best practice is to create a single namespace for your code that you then put all your other variables into, so that you don't pollute the global namespace. So really it should be something like:
<script type="text/javascript">
var MyApp = {};
MyApp.dropdownData = #Html.Raw(Json.Encode(Model.MyArray));
</script>
But the first block of code I provided would be fine to get started with.
leora,
I was inspired by the following solution for sending 'lists' from javascript to and mvc action:
var leadIds = $('input.chkTileSelector:checked').map(function () {
return { name: 'leadIds', value: $(this).parents('div.Lead').data('id') };
}).get();
$.ajax({
url: '#Url.Action("UnParkLeads", "Lead")',
type: 'POST',
dataType: 'json',
data: leadIds,
success: function (result) {
ReloadResultGrid();
}
});
you can see the article here:
http://zootfroot.blogspot.com/2011/09/jquery-post-javascript-array-to-aspnet.html