Javascript not working when jquery is added - javascript

I am new to javascript n jquery. I used javascript along with jquery on my script tag.When jquery is not added, the javascript works fine,but when a jquery function is added, the script is not working.....shall i convert both to javascript or both to jquery or am i missing anything.Here is my script
<script type="text/javascript">
function getLocations() {
$.post('#Url.Action("getLocations","Home")', { 'id': $("#cities").val() },
function (data) {
$("#loca").html(data).show();
});
}
$(function () {
$('.submit').on('click', function () {
var ck = "";
var city = $("#cities option:selected").text();
var location = $("#loca option:selected").text();
alert(city+"and"+location)
}
});
</script>
here i am loading location based on the city selected.Its works fine when the onclick is not there,But when added ,location are not loading n the function is not calling.I have tried by butting alert inside it.Do i need do any thing else for both to work....Thank You

you forgot a )
$(function () {
$('.submit').on('click', function () {
...
}) // <---
});
if you properly indent the code blocks and if you look on the javascript console, this kind of errors become easier to be detected. Just adopt an indent style and write code adhering to it.

Related

jquery methods are not firing with css class names after moving to js file?

below methods are working fine when I have them in razor or partial views. after them to JS from these are not at all. JS file is loading and other regular javascript methods working fine. What could be the wrong?
$('.phonelocation').on('change', function () {
$("#HdnCommunicationLocation").val(this.value); // or $(this).val()
});
$('.phonetype').on('change', function () {
$("#HdnCommunicationType").val(this.value); // or $(this).val()
$('.phoneCountry').trigger('change');
});
$('.phoneCountry').change(function () {
..
}
You must add the js after the document is loaded.
$(document).ready(function () {
$(document).on('change', '.phonelocation', function () {
$("#HdnCommunicationLocation").val(this.value); // or $(this).val()
});
$(document).on('change', '.phonetype', function () {
$("#HdnCommunicationType").val(this.value); // or $(this).val()
$('.phoneCountry').trigger('change');
});
$(document).on('change', '.phoneCountry', function () {
..
}
});
update: try adding the events to the document that way no matter when the elwments are added the events will still work

how to pass parameter in jquery using .on?

Good Day, this maybe a silly question :) how can I pass a parameter to an external javascript function using .on ?
view:
<script>
var attachedPo = 0;
$this.ready(function(){
$('.chckboxPo').on('ifChecked', addPoToBill(attachedPo));
$('.chckboxPo').on('ifUnchecked', removePoToBill(attachedPo ));
});
</script>
external script:
function addPoToBill(attachedPo){
attachedPo++;
}
function removePoToBill(attachedPo){
attachedPo--;
}
but Im getting an error! thanks for guiding :)
You need to wrap your handlers in anonymous functions:
$('.chckboxPo')
.on('ifChecked', function() {
addPoToBill(attachedPo);
})
.on('ifUnchecked', function() {
removePoToBill(attachedPo);
});
You can also chain the calls to on as they are being attached to the same element.
If your intention is to count how many boxes are checked, via passing variable indirectly to functions try using an object instead like this:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/pBkhX/
var attachedPo = {
count: 0
};
$(function () {
$('.chckboxPo')
.on('change', function () {
if ($(this).is(':checked')) {
addPoToBill(attachedPo);
} else {
removePoToBill(attachedPo);
}
$("#output").prepend("" + attachedPo.count + "<br/>");
});
});
function addPoToBill(attachedPo) {
attachedPo.count++;
}
function removePoToBill(attachedPo) {
attachedPo.count--;
}
If it is not doing anything else you can simplify the whole thing to count checked checkboxes:
$(function () {
var attachedPo = 0;
$('.chckboxPo')
.on('change', function () {
attachedPo = $(".chckboxPo:checked").length;
});
});
"DOM Ready" events:
you also needed to wrap it in a ready handler like this instead of what you have now:
$(function(){
...
});
*Note: $(function(){YOUR CODE HERE}); is just a shortcut for $(document).ready(function(){YOUR CODE HERE});
You can also do the "safer version" (that ensures a locally scoped $) like this:
jQuery(function($){
...
});
This works because jQuery passes a reference to itself through as the first parameter when your "on load" anonymous function is called.
There are other variations to avoid conflicts with other libraries (not very common as most modern libs know to leave $ to jQuery nowadays). Just look up jQuery.noConflict to find out more.

Can some tell me where is the error? saying $ not defined, object expected

saying $ not defined, object expected.. actually i want to verify if all set of radio button check when a button is clicked! help plz
<script type="text/javascript">
$(document).on('click', 'form', function () {
var validate = true;
var unanswered = new Array();
// Loop through available sets
$('.qselections').each(function () {
// Question text
var question = $(this).prev().text();
// Validate
if (!$(this).find('input').is(':checked')) {
// Didn't validate ... dispaly alert or do something
unanswered.push(question);
validate = false;
}
});
if (unanswered.length > 0) {
msg = "Please answer the following questions:\n" + unanswered.join('\n');
alert(msg);
}
return validate;
});
</script>
Did you forget to include the jquery.js file in your markup before your code?
A generally accepted way to set up your script references is as follows (there are others, this isn't the be-all-end-all):
<html>
<head>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="MyScriptFile.js"></script>
<script>
$(function() {
$(document).on('click', 'form', function () {
var validate = true;
var unanswered = new Array();
// Loop through available sets
$('.qselections').each(function () {
// Question text
var question = $(this).prev().text();
// Validate
if (!$(this).find('input').is(':checked')) {
// Didn't validate ... dispaly alert or do something
unanswered.push(question);
validate = false;
}
});
if (unanswered.length > 0) {
msg = "Please answer the following questions:\n" + unanswered.join('\n');
alert(msg);
}
return validate;
});
</script>
</body>
</html>
This way you can be sure that (1) your page is loaded before any scripts try to do scripty things and (2) you have included jQuery before other scripts which may want to use it.
This is not foolproof, and you may (eventually) need to use something like Require.js or as a simpler step the defer attribute.
1.Have you included Jquery lib in first script tag in your head section. In that case only your jquery based code will execute.
2.Did you wrap the code into $(document).ready() function.
3 Are you using PHP at your corners. So need to replace $ with Jquery.

NicEdit interfering with JQuery $ alias

I am implementing the NicEdit editor with our own rich textbox ASP.NET control, which is just composite control that includes a TextArea and registers the NicEdit scripts on document ready.
The rich textbox control (and all our pages/controls) are also using JQuery.
The problem is that for some reason a piece of the NicEdit code's nulls out the "$" JQuery alias.
The following line of code executes when the control is loading:
onDomLoaded: function (A) {
debugger;
this.domLoad.push(A);
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", bkLib.domLoaded, null)
}
else {
if (bkLib.isMSIE) {
document.write("<style>.nicEdit-main p { margin: 0; }</style><script id=__ie_onload defer "+((location.protocol=="https:")?"src='javascript:void(0)'":"src=//0")+"><\/script>");
$BK("__ie_onload").onreadystatechange = function () {
if (this.readyState == "complete") {
bkLib.domLoaded()
}
}
}
} window.onload = bkLib.domLoaded
}
The specific line of code I am talking about is:
document.write("<style>.nicEdit-main p { margin: 0; }</style><script id=__ie_onload defer "+((location.protocol=="https:")?"src='javascript:void(0)'":"src=//0")+"><\/script>");
Before this executes, the $ alias points to JQuery, after the execution of that line, it is undefined.
I cannot seem to figure out what this line is suppose to do and why does it mess with the $ JQuery alias.
Could anyone suggest what is going on here?
Seems like the onDomLoaded function does not work good, so I used JQuery $(document).ready()
Before:
$(document).ready(function () {
bkLib.onDomLoaded(function() { new nicEditor().panelInstance('area1'); });
});
After:
$(document).ready(function () {
new nicEditor().panelInstance('id');
});

Calling a function (ex. namespace.show) by name

I want to call a function with a namespace based on its name.
Perhaps some background: What I want is, dynamically bind pages via $.mobile.loadPage(inStrUrl, { showLoadMsg: false }); and then, based on the current page, invoke a function within a loaded page. For example: each page has a showFilter function, the Event is attached to a main.html - page which should call the matching function in the current page.
I also tried some solutions, with jquery too, but nothing works for me.
This is my function code:
function namespace() { }
namespace.showFilter = function () {
alert("Test");
}
And want to "invoke" or "call" it via its name.
This is what i tried at least.
$(document).ready(function() {
var fn = window["namespace.showFilter"];
fn();
});
I get error TypeError: fn is not a function
Here is a fiddle http://jsfiddle.net/xBCes/1/
You can call it in the following way:
$(document).ready(function() {
window["namespace"]["showFilter"]();
});
or
$(document).ready(function() {
window["namespace"].showFilter();
});
or
$(document).ready(function() {
window.namespace.showFilter();
});
I found that I had to manually set it to window.
window.namespace = function() { }
window.namespace.showFilter = function () {
alert("Test");
};
$(document).ready(function() {
var fn = window["namespace"]["showFilter"];
fn();
});
http://jsfiddle.net/xBCes/4/
Like this:
$(function() {
window.namespace.showFilter();
});
P.S. I shortened the $(document).ready(...)
function namespace() {}
namespace.showFilter = function () {
alert("Test");
}
$(document).ready(function() {
var fn = namespace.showFilter();
fn();
});
http://jsfiddle.net/xBCes/3/

Categories

Resources