I know you are supposed to be able to break out of an each statement by returning, which is what I'm trying to do, but I must be doing something wrong and it seems so simple I can't find it.
I have code like this
function create() {
var test = hasThing();
if (test) {
$('#myForm').submit();
} else {
alert('you suck!')
}
}
function hasThing() {
$('.selects').each(function() {
if (this.value != "") {
return true;
}
});
return false;
}
I have set breakpoints on "return true;" and hit it but var test is always false because for some reason the .each() loop continues and the hasThing() function continues. I've tried switching things around so that I return false in the .each() just in case for some reason that mattered but it didn't change anything.
I don't get it. Seems counter to how the documentation says it should work.
Your return true; statement returns from the anonymous function given to each. The return false; line is always executed which explains why var test is always false.
Change your code to
function hasThing() {
var hasThing = false;
$('.selects').each(function() {
if (this.value != "") {
hasThing = true;
return false; // breaks the $.each, but does not return from hasThing()
}
});
return hasThing;
}
You could use Array.some() to check if any of the selects have a selected value
function hasThing() {
return $('select').toArray().some(function(el) {
return el.value != "";
})
}
function create() {
var test = hasThing();
if (test) {
alert('at least one select was changed');
//$('#myForm').submit();
} else {
alert('you suck!');
}
}
function hasThing() {
return $('select').toArray().some(function(el) {
return el.value != "";
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Select at least one option !</p>
<form id="myForm">
<select class="selects">
<option value="">blank</option>
<option value="2">option1</option>
</select>
<select class="selects">
<option value="">blank</option>
<option value="2">option1</option>
</select>
<input type="button" onclick="create()" value="submit" />
</form>
Related
I'm trying to change inputX[0] from false to true, then get an alert if it worked. Unfortunately I don't get the message that inputX[0] was set to true. Do you have any ideas?
<body>
<div>
<button id="S1" onclick="btnManager(this);"></button>
</div>
<script>
var inputX = new Array();
definedInputs();
btnManager();
question();
function definedInputs() {
inputX[0] = false;
}
function btnManager(pressedBtn) {
if (pressedBtn.id == (id = "S1")) {
inputX[0] = true;
}
}
function question() {
if (inputX[0] == true) {
alert("inputX is set to true");
}
}
</script>
</body>
try with this:
<body>
<div>
<button id="S1" onclick="btnManager(this);"></button>
</div>
<script>
var inputX = new Array();
inputX[0] = false;
function btnManager(pressedBtn) {
inputX[0] = !inputX[0];
alert(inputX[0]);
}
</script>
</body>
With this, every you push the button the value will be set by the negation of the current value, hope it helps.
It is important that you understand the Js lifecycle.
First javascript objects and functions are built and
then the code is executed, in this case it happens as follows:
The array "inputX" is created
Using the function "definedInputs()" defines "inputX[0] = false"
"btnManager()" is executed but since it is not assigned a parameter, the value of "pressedBtn.id" is "undefined" so the state of "inputX[0]" does not change
The status of "inputX[0]" is queried using "question()", but since "inputX[0]" is still false, no alert is fired.
All of this happens before you can press the button.
Pressing the button executes "btnManager(this)" and since the id is equal to "S1" the state of "inputX[0]" changes to true.
But you can't see this change because the "question()" function has already been executed.
Try:
<!DOCTYPE html>
<html>
<body>
<div>
<button id="S1" onclick="btnManager(this);">Test</button>
</div>
<script>
var inputX = new Array();
definedInputs();
function definedInputs() {
inputX[0] = false;
}
function btnManager(pressedBtn) {
if (pressedBtn.id == "S1") {
inputX[0] = true;
}
question();
}
function question() {
if (inputX[0] == true) {
alert("inputX is set to true");
}
}
</script>
</body>
</html>
Add some console logs to see what is happening. If you do, you'll see that all of your functions are executing immediately. When you click the button and enter the btnManager() function what happens next? As you'll see, your code is executing the btnManager() function but then what about checking for your alert?
If you call question() after your if statement, then you'll run your check again.
You could do this with less lines, but for the sake of keeping your exact code and making it work, this is how you would achieve your goal:
<body>
<div>
<button id="S1" onclick="btnManager(this);"></button>
</div>
<script>
var inputX = new Array();
// You could really remove these and do it like Lucretius's Answer
definedInputs();
btnManager();
question();
function definedInputs() {
inputX[0] = false;
}
function btnManager(pressedBtn) {
if (pressedBtn.id == (id = "S1")) {
inputX[0] = true;
}
question();
}
function question() {
if (inputX[0] == true) {
alert("inputX is set to true");
}
}
</script>
</body>
You're comparing the value of pressedBtn.id which is a text string S1 to a true/false Boolean evaluation (id == "S1") which will always be false because text strings and boolean values are not the same. Since (id = "S1") is an assignment, and you can't compare an assignment, this is what I am guessing you're trying to do.
'S1' == true will always be false
'S1' == false will also always be false.
Instead of:
function btnManager(pressedBtn) {
if (pressedBtn.id == (id == "S1")) {
inputX[0] = true;
}
}
Just evaluate the id and then log it to console to make sure the input array is updated.
<body>
<div>
<button id="S1" onclick="btnManager(this);">Click</button>
</div>
<script>
var inputX = new Array();
definedInputs();
function definedInputs() {
inputX[0] = false;
}
function btnManager(pressedBtn) {
if (pressedBtn.id == "S1" ) { //fixed
console.log( pressedBtn.id == (id == "S1") ); // breaks, undefined
}
}
function question() {
if (inputX[0] == true) {
alert("inputX is set to true");
}
}
</script>
</body>
Here is your code fixed.
You don't need to call btnManager(); or question(); immediately since these are called in a cascading fashion after the button click event is fired. The only "pre-work" your code needs to do on load is to defineInputs(); so those two lines were removed.
<body>
<div>
<button id="S1" onclick="btnManager(this);">Click</button>
</div>
<script>
var inputX = new Array();
definedInputs();
function definedInputs() {
inputX[0] = false;
}
function btnManager(pressedBtn) {
if (pressedBtn.id == "S1") {
inputX[0] = true;
console.log( "true" );
}
}
function question() {
if (inputX[0] == true) {
alert("inputX is set to true");
}
}
</script>
</body>
Well, the question's pretty self-explanatory. I've been looking for a while and haven't found a proper way to do this kind of validation.
All I need to do is to run an error message if all the inputs are empty. If one of them is filled, then I don't need to stop the form from submitting.
I thought something like:
function checkForm() {
$('input').each(function(){
if( $(this).val() == "" ){
return false;
}
});
});
But this will stop my form if there's, at least, one input without data.
Any ideas? Thanks in advance.
Reverse your logic. I.e. return true if any input has a value, otherwise return false:
function checkForm() {
$('input').each(function() {
if ($(this).val() !== '') {
return true;
}
});
return false;
};
Reverse your logic since you want to check if the value is non-empty for one input field.
Also you probably want to return from your actual function and not from the callback which has no effect.
function checkForm() {
let bool = false;
$('input').each(function(){
if( $(this).val() !== '' ){
bool = true;
}
});
console.log(bool);
return bool;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<input type="text">
<input type="text">
<button onclick="checkForm()">check</button>
I would like to check if the mark I selected and input value are the same or not, but the alert in js works even though when they are same. Here is my code! Thanks for your support!
HTML
<select id="mark">
<option value="o">o</option>
<option value="x">x</option>
</select>
<input type="text" name="block%s" id="block" onchange="check()">
JS
var mark = document.getElementById("mark").value;
var block = document.getElementById("block").value;
function check() {
if (block != mark) {
alert ('Your mark is wrong');
return false;
} else {
return true;
}
}
You need to put these variables inside function, otherwise there values are determined at the beginning and won't change afterwards.
function check(){
var mark=document.getElementById("mark").value;
var block=document.getElementById("block").value;
if( block != mark) {
alert ('Your mark is wrong');
return false;
}
else{
return true;
}
}
<select id="mark">
<option value="o">o</option>
<option value="x">x</option>
</select>
<input type="text" name="block%s" id="block" onchange="check()">
First of all create the function check() .
You can get value of options by selectedIndex or selectedValue
var e = document.getElementById("mark");
var strUser = e.options[e.selectedIndex].value;
after that compare the value of selectedValue and input text and display appropriate message according to need in alert
Your JavaScript code should be like this : (The block var declared after the function)
<script>
var mark=document.getElementById("mark").value;
function check() {
var block = document.getElementById("block").value;
console.log(mark + '-' + block)
if (block != mark) {
alert ('Your mark is wrong');
return false;
} else {
return true;
}
}
</script>
The function check should include all variables. Here, Try this:
function check(){
var mark=document.getElementById("mark").value;
var block=document.getElementById("block").value;
if(block != mark) {
alert ('Your mark is wrong');
return false;
}
else{
alert ('Your mark is right');
return true;
}
}
Variables should be inside function
Try following:
HTML
<input type="text" name="block%s" id="block" onchange="check(this)">
Javscript
function check(inputBox) {
var markBox = document.getElementById("mark");
var mark = markBox[markBox.selectedIndex].value;
var block = inputBox.value;
if (block != mark) {
alert ('Your mark is wrong');
return false;
} else {
return true;
}
}
You can also use onblur of input box to call check() when user leaves the input box.
I have a TS code like this:
class MicrositeRequest {
micrositeName: string;
micrositeTemplate: string;
constructor() {
this.micrositeName = $("#micrositeNameId").val();
this.micrositeTemplate = $("#templateId option:selected").text();
}
public IsMicrositeRequestValid() {
if (this.checkForName() && this.checkForTemplate()) {
return true;
}
else {
return false;
}
}
checkForName() {
if (this.micrositeName != null && this.micrositeName.length != 0) {
return true;
}
else {
return false;
}
}
checkForTemplate() {
if (this.micrositeTemplate != null && this.micrositeTemplate.length != 0) {
return true;
}
else {
return false;
}
}
}
Here's the converted JS:
/// <reference path="scripts/typings/jquery/jquery.d.ts" />
var MicrositeRequest = (function () {
function MicrositeRequest() {
this.micrositeName = $("#micrositeNameId").val();
this.micrositeTemplate = $("#templateId option:selected").text();
}
MicrositeRequest.prototype.IsMicrositeRequestValid = function () {
if (this.checkForName() && this.checkForTemplate()) {
return true;
}
else {
return false;
}
};
MicrositeRequest.prototype.checkForName = function () {
if (this.micrositeName != null && this.micrositeName.length != 0) {
return true;
}
else {
return false;
}
};
MicrositeRequest.prototype.checkForTemplate = function () {
if (this.micrositeTemplate != null && this.micrositeTemplate.length != 0) {
return true;
}
else {
return false;
}
};
return MicrositeRequest;
})();
//# sourceMappingURL=Microsite.js.map
On Click of a button I want to call the IsMicrositeRequestValid() method.
Here's the HTML:
<div>
<input type="submit" name="submit" value="Get" onclick="IsMicrositeRequestValid()" />
</div>
The Console says IsMicrositeRequestValid is not defined.
Any clues why this is happening and how I can fix it?
The call to IsMicrositeRequestValid in the onclick attribute requires that the function be part of the global namespace (window). Further, I'm pretty sure you'll need to instantiate MicrositeRequest object before the call to IsMicrositeRequestValid work (because it relies on this).
function validateRequest() { // declare a function in the global namespace
var mr = new MicrositeRequest();
return mr.IsMicrositeRequestValid();
}
<input type="submit" name="sumbit" value="Get" onclick="validateRequest()" />
is the quick & dirty way which should get it working.
You could also do this:
window.validateRequest = function () { // declare a function in the global namespace
var mr = new MicrositeRequest();
return mr.IsMicrositeRequestValid();
}
which I think is more readable.
Also, look into the Element.addEventListener method. It allows much more flexibility.
var submit = document.getElementById('my-submit');
submit.addEventListener('click', function () {
var mr = new MicrositeRequest();
return mr.IsMicrositeRequestValid();
});
<input type="submit" id="my-submit" name="sumbit" value="Get" />
In addition to pete's answer here an object oriented solution:
Alex works with jQuery, so i feel free to use it in this answer.
1.
You can't call methods of a class but only methods of objects, so you have to instantiate a object of class MicrositeRequest somewhere. Usually you do this after the DOM is fully populated, so you write:
$(() => {
new MicrositeRequest();
});
You may place this code beneath your class definition so that it starts after the browser loaded your script.
2.
Give your input element an id:
<div>
<input id="myInputElement" type="submit" name="submit" value="Get" onclick="IsMicrositeRequestValid()" />
</div>
Register method IsMicrositeRequestValid of the MicrositeRequest-object as onClick-handler for your input-element. To achieve this add these lines to the constructor method of class MicrositeRequest:
let that = this;
$('#myInputElement').on('click', () => {
that.IsMicrositeRequestValid();
});
You need variable that because inside the event handler this points to the input element.
Basically I have a script the function "hola ()" that should return the value of 1 if the radio button value is 1. But for some reason when I try to get the return value in another function i never get it.
The form works perfectly.. the only issue is that it doesnt return the value
Can anyone tell me what i did wrong?? thanks
$(document).ready(function(){
function hola() {
$("form[name=yN]").show("slow");
$('input[type=radio]').click( function (){
var opt = $(this).attr("value");
if (opt == "1") {
this.checked = false;
$("form[name=yN]").hide("slow");
return 1;
}
if (opt == 0) {
$("p").html ("ok");
this.checked = false;
}
})
}
$("#iForm").submit( function(event){
event.preventDefault();
var user = $("input[name=username]").val();
var password = $("input[name=password]").val();
var dbName = $("input[name=dbName]").val();
var server = $("input[name=server]").val();
$.get("1.php",
{username: user, password: password, dbName: dbName, server: server },
function(data){
if (data == "The table PAGE exists" || data == "The table SUBJECTS exists" || data == "The table USERS exists" ) {
// CALLING THE hola () function and expecting a return
var opt = hola();
$("p").html(data + opt);
}
}
)
})
})
HTML
<!-- Yes or No form -->
<form name="yN" style= "display: none; margin-left: auto; margin-right: auto; width: 6em">
<input type="radio" name="yN" value="1">yes</input>
<input type="radio" name="yN" value="0">no</input>
<button id=1 >click me!</button>
</form>
<!-- Login Form -->
<form id="iForm" style= "display: show">
<label id="username" >Username</label>
<input id="username" name="username"/>
<label id="password">Password</label>
<input id="password" name="password" />
<label id="server" >Server</label>
<input id="server" name="server"/>
<label id="dbName" >dbName</label>
<input id="dbName" name="dbName"/>
<input type="submit" value="submit" />
</form>
<p> </p>
Event handlers cannot return values because they're called asynchronously*.
Your existing hola() function will return immediately and the return statements in the click handlers are only called much later, i.e. when the button is clicked.
My approach would be this, using jQuery deferred objects (jQuery 1.6+):
function hola() {
var def = $.Deferred();
// show the popup confirm form
...
$('input[type=radio]').click(function() {
// determine return value
...
// send it back to anything waiting for it
def.resolve(retval);
});
// return a _promise_ to send back a value some time later
return def.promise();
}
$.get("1.php", { ... }).done(function(data) {
if (...) {
hola().done(function(opt)) { // will be called when the promise is resolved
$("p").html(data + opt);
});
}
});
If you prefer, instead of returning the opt value you could use def.reject() to indicate "non-acceptance" and then use a .fail handler to register a handler to be called for that condition.
You return 1 only in the click function of the radiobutton.
If you want to have a function "hola" that returns 1 if the radiobutton is checked, you simply need something like this:
function hola() {
return $("input:radio[name='yN']:checked").val();
}
hola does not even have a return statement. That's the reason for its not returning anything (more precisely: returning undefined always).
A JavaScript function that does not contain a return statement at all or whose all return statements are within nested functions will never return anything but undefined.
Your are tring to return the value from withing the click callback function. Move the return outside that:
function hola() {
var result;
$("form[name=yN]").show("slow");
$('input[type=radio]').click( function (){
var opt = $(this).attr("value");
if (opt == "1") {
this.checked = false;
$("form[name=yN]").hide("slow");
result = 1;
}
if (opt == 0) {
$("p").html ("ok");
this.checked = false;
}
});
return result;
}