Basically, I want to change value on, say textbox2, when the value of textbox1 is changed by a button function. I know that it is possible to include the function on the button to change the value on the textbox2, but I don't want that. Is it possible?
Here's what I tried so far on JSFiddle https://jsfiddle.net/xpvt214o/387300/
HTML code:
<button id="button1">button</button>
<input type="text" id="outputtext1" value="1" readonly/>
<input type="text" id="outputtext2" value="" />
JavaScript:
jQuery('#button1').on('click', function() {
document.getElementById("outputtext1").value = parseInt(document.getElementById("outputtext1").value) +1;
});
jQuery('#outputtext1').on('change', function() {
//I know that this logic can be put in onClick function above instead
var number = document.getElementById("outputtext1").value;
if( number <= 3){
document.getElementById("outputtext2").value = "low";
} else if (number < 10){
document.getElementById("outputtext2").value = "medium";
} else if (number >= 10){
document.getElementById("outputtext2").value = "high";
}
});
Thank you in advance!
You can use jQuery('#outputtext1').trigger("change"); in the button element click event.
Example:
jQuery('#button1').on('click', function() {
document.getElementById("outputtext1").value = parseInt(document.getElementById("outputtext1").value) + 1;
jQuery('#outputtext1').trigger("change");
});
jQuery('#outputtext1').on('change', function() {
var number = document.getElementById("outputtext1").value;
if (number <= 3) {
document.getElementById("outputtext2").value = "low";
} else if (number < 10) {
document.getElementById("outputtext2").value = "medium";
} else if (number >= 10) {
document.getElementById("outputtext2").value = "high";
}
});
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1">button</button>
<input type="text" id="outputtext1" value="1" readonly/>
<input type="text" id="outputtext2" value="" />
Try this:Change the value for outputtext1 and fire change event on it
jQuery('#button1').on('click', function() {
var value = jQuery("#outputtext1").val();
value = (parseInt(value) || 0) + 1;
jQuery("#outputtext1").val(value).change();
});
jQuery('#outputtext1').on('change', function() {
var number = (parseInt($(this).val()) || 0) + 1;
if( number <= 3){
jQuery("#outputtext2").val("low");
} else if (number < 10){
jQuery("#outputtext2").val("medium");
} else if (number >= 10){
jQuery("#outputtext2").val("high");
}
});
JSFiddle
NOTE: You can use jQuery id selector and '.va()` function instead of Javacript as shown in code above.
You could use $('#outputtext1').trigger("change") on button click
DEMO
$('#button1').on('click', function() {
$('#outputtext1').val(+$('#outputtext1').val()+1);
$('#outputtext1').trigger("change");
});
$('#outputtext1').on('change', function() {
var number = document.getElementById("outputtext1").value;
if (number <= 3) {
document.getElementById("outputtext2").value = "low";
} else if (number < 10) {
document.getElementById("outputtext2").value = "medium";
} else if (number >= 10) {
document.getElementById("outputtext2").value = "high";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1">button</button>
<input type="text" id="outputtext1" value="1" readonly/>
<input type="text" id="outputtext2" value="" />
Either you can trigger the change event or create a generic function and call it on both click and change event. Its better to call generic function rather then triggering the event from event.
// find elements
var banner = $("#banner-message")
var button = $("button")
$('#button1').on('click', function() {
document.getElementById("outputtext1").value = parseInt(document.getElementById("outputtext1").value) + 1;
$('#outputtext1').trigger('change');
});
$('#outputtext1').on('change', function() {
var number = document.getElementById("outputtext1").value;
if (number <= 3) {
document.getElementById("outputtext2").value = "low";
} else if (number < 10) {
document.getElementById("outputtext2").value = "medium";
} else if (number >= 10) {
document.getElementById("outputtext2").value = "high";
}
});
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1">button</button>
<input type="text" id="outputtext1" value="1" />
<input type="text" id="outputtext2" value="" />
<!-- this should be changed when the value of outputtext1 is changing -->
// find elements
var banner = $("#banner-message")
var button = $("button")
$('#button1').on('click', function() {
document.getElementById("outputtext1").value = parseInt(document.getElementById("outputtext1").value) + 1;
validateInput();
});
$('#outputtext1').on('change', function() {
validateInput();
});
function validateInput() {
var number = document.getElementById("outputtext1").value;
if (number <= 3) {
document.getElementById("outputtext2").value = "low";
} else if (number < 10) {
document.getElementById("outputtext2").value = "medium";
} else if (number >= 10) {
document.getElementById("outputtext2").value = "high";
}
}
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1">button</button>
<input type="text" id="outputtext1" value="1" />
<input type="text" id="outputtext2" value="" />
<!-- this should be changed when the value of outputtext1 is changing -->
try this fiddle
I am getting the selector attribute value with $('#outputtext1').attr('value') so that it will not break and change the value at runtime[Please check the value in DOM]. At the same time I am triggering a change event on button click.
jQuery('#button1').on('click', function() {
var x = $('#outputtext1').attr('value');
x = parseInt(x) +1;
$('#outputtext1').attr("value", x);
jQuery('#outputtext1').trigger("change");
});
jQuery('#outputtext1').on('change', function() {
var number = $('#outputtext1').attr('value');
if( number <= 3){
document.getElementById("outputtext2").value = "low";
} else if (number < 10){
document.getElementById("outputtext2").value = "medium";
} else if (number >= 10){
document.getElementById("outputtext2").value = "high";
}
});
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1">button</button>
<input type="text" id="outputtext1" value="1" />
<input type="text" id="outputtext2" value="" />
Related
I have this code to validate 2 input text, but how can I validate same input for
dynamic intput text ? meaning input text quantity can be up to 100 or more.
<input type="text" id="id1" />
<input type="text" id="id2" />
$('input').blur(function() {
if ($('#id1').attr('value') == $('#id2').attr('value')) {
alert('Same Value');
return false;
} else { return true; }
});
If you want to check all the inputs are the same (I gather that's what you're trying to do) you could just loop through them by using a function like this:
function validate() {
for (var i = 2; i <= 100; i++) {
if ($('#id' + x).val() !== $('#id' + (x - 1)).val()) {
return false;
}
}
return true;
}
Of course, you may want to create inputs themselves using a loop too if you'll have that many on the page.
<input type="text" id="id1" onblur="validate()">
<input type="text" id="id2" onblur="validate()">
<p style="display: none">Test</p>
<script type="text/javascript">
function validate() {
for (var i = 1; i <= 2; i++) {
if ($('#id' + i).val() == $('#id' + (i - 1)).val()) {
$( "p" ).show( "slow" ); return false;
}
else
{
$( "p" ).hide( 1000 );
}
}
return true;
}
</script>
What I did is this hope someone can you this in future reference
I'm creating a "Sign Up" form for my new website, but got a problem with a jQuery/JS function that is supposed to check for some conditions to be reached.
$(function checkform() {
if (this.is("#username")) {
var validchars = /^[a-zA-Z0-9\s]+$/;
var nameHasError;
if (this.val().length < 6 && this.val().length > 26) {
nameHasError = true;
this.parent("div").addClass("has-error");
} else if (!(validchars.test(this).val())) {
nameHasError = true;
this.parent("div").addClass("has-error");
} else {
nameHasError = false;
this.parent("div").removeClass("has-error");
};
} else if (this.is("#password")) {
var passHasError;
if (this.val().length < 5 && this.val().length > 45) {
passHasError = true;
this.parent("div").addClass("has-error");
} else {
passHasError = false;
this.parent("div").removeClass("has-error");
};
};
});
Here's the JSFiddle with HTML part (I'm using bootstrap on my website but preferred to set a specific class on the fiddle)
Best regards
You are mixing vanilla javascript with jquery syntax. this.is('#username') is not javascript.
Use this.id == "username" (vanilla js) instead
OR
$(this).is('#username') (jquery)
Take care with the scope in your functions
There are multiple issues in the code
You have defined the checkForm in $(), so the function will be available only inside the dom ready handler, so your onkeypress will throw an error
When dom ready handler invokes the function this will be the document object which does not have the is function
The character size validation should use || not &&
So, ti will be better to use a jQuery event handler with both the fields having their own validation function like
jQuery(function($) {
$('#username').on('keypress', function() {
var validchars = /^[a-zA-Z0-9\s]+$/;
var nameHasError = false;
var $this = $(this),
value = this.value;
if (value.length < 6 || value.length > 26) {
nameHasError = true;
} else if (!validchars.test(value)) {
nameHasError = true;
};
$this.parent("div").toggleClass("has-error", nameHasError);
});
$('#password').on('keypress', function() {
var passHasError = false;
var $this = $(this),
value = this.value;
if (value.length < 5 || value.length > 45) {
passHasError = true;
};
$this.parent("div").toggleClass("has-error", passHasError);
});
});
.has-error {
background-color: red;
}
.has-success {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" placeholder="Between 6 and 26 characters">
<span id="unameError"></span>
</div>
<br/>
<div class="">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password">
<span id="passError"></span>
</div>
</div>
function checkform() {
if ($(this).is("#username")) {
var validchars = /^[a-zA-Z0-9\s]+$/;
var nameHasError;
if ($(this).val().length < 6 || $(this).val().length > 26) {
nameHasError = true;
$(this).parent("div").addClass("has-error");
} else if (!(validchars.test($(this).val()))) {
nameHasError = true;
$(this).parent("div").addClass("has-error");
} else {
nameHasError = false;
$(this).parent("div").removeClass("has-error");
};
} else if ($(this).is("#password")) {
var passHasError;
if ($(this).val().length < 5 || $(this).val().length > 45) {
passHasError = true;
$(this).parent("div").addClass("has-error");
} else {
passHasError = false;
$(this).parent("div").removeClass("has-error");
};
};
}
$(function () {
$('input').on('keyup', checkform);
})
.has-error {
background-color: red;
}
.has-success {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" placeholder="Between 6 and 26 characters">
<span id="unameError"></span>
</div>
<br/>
<div class="">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password">
<span id="passError"></span>
</div>
</div>
I want to dynamically add and remove input files, my code works great on all browsers without Internet Explorer. Can anyone help me to resolve my problem?
Here is the Javascript:
<script>
var counter = 1;
var min = 1;
var max = 20;
function addInput(divName) {
if (counter == max) {
alert("Max limit!");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = '<input type="file" name="file[]" id="file"><br>';
document.getElementById(divName).appendChild(newdiv);
document.getElementById("qty").value++;
counter++;
}
}
function remInput(divName) {
if (counter == min) {
alert("Min limit!");
}
else {
var element = document.getElementById(divName);
element.lastChild.remove();
document.getElementById("qty").value--;
counter--;
}
}
</script>
And here is the HTML code:
<input type="button" value="-" onClick="remInput('plus');">
<input type="text" name="qty" id='qty' size='2' style="text-align: center" disabled value="1">
<input type="button" value="+" onClick="addInput('plus');">
<div id="plus">
<input type="file" name="file[]" id="file"><br>
</div>
Thank you.
Its seems that remove() is not supported in IE, do add condition in your code, if particular function is supported in your browser(in this case remove() function)
Please refer below working add.
<script>
var counter = 1;
var min = 1;
var max = 20;
function addInput(divName) {
if (counter == max) {
alert("Max limit!");
}
else {
var newdiv = document.createElement('div');
var inputid="file"+counter;
newdiv.innerHTML = '<input type="file" name="file[]" id='+inputid+'><br>';
document.getElementById(divName).appendChild(newdiv);
document.getElementById("qty").value++;
counter++;
}
}
function remInput(divName) {
if (counter == min) {
alert("Min limit!");
}
else {
var element = document.getElementById(divName);
if(element.lastChild.remove!= undefined)
element.lastChild.remove();
else
element.lastChild.parentNode.removeChild(element.lastChild);
document.getElementById("qty").value--;
counter--;
}
}
</script>
http://jsfiddle.net/R89fn/9/
If any of the text input/Box added are empty then the page must not submit.when I try to retrieve values from the text inputs using their id`s nothing gets retrieved is it possible to retrieve values from elements added dynamically?
$("#submit").click(function (event) {
var string = "tb";
var i;
for (i = 1; i <= count; i++) {
if (document.getElementById(string+1).value=="") {
event.preventDefault();
break;
}
}
});
The above code is what I am using to get the value from the text fields using there id
I took a look on the code in the JSFiddle. It appears that the input textboxes are not given the intended IDs; the IDs are given to the container div.
The code for the add button should use this,
var inputBox = $('<input type="text" id="td1">') //add also the needed attributes
$(containerDiv).append(inputBox);
Check out this solution on fiddle: http://jsfiddle.net/R89fn/15/
var count = 0;
$(document).ready(function () {
$("#b1").click(function () {
if (count == 5) {
alert("Maximum Number of Input Boxes Added");
} else {
++count;
var tb = "tb" + count;
$('#form').append("<div class=\"newTextBox\" id=" + tb + ">" + 'InputField : <input type="text" name="box[]"></div>');
}
});
$("#b2").click(function () {
if (count == 0) {
alert("No More TextBoxes to Remove");
} else {
$("#tb" + count).remove();
--count;
}
});
$("#submit").click(function (event) {
var inputBoxes = $('#form').find('input[type="text"]');;
if (inputBoxes.length < 1) {
alert('No text inputs to submit');
return false;
} else {
inputBoxes.each(function(i, v) {
if ($(this).val() == "") {
alert('Input number ' + (i + 1) + ' is empty');
$(this).css('border-color', 'red');
}
});
alert('continue here');
return false;
}
});
});
<form name="form" id="form" action="htmlpage.html" method="POST">
<input type="button" id="b1" name="b1" value="Add TextBox" />
<input type="button" id="b2" name="b2" value="Remove TextBox" />
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script>
var count = 0;
$(document).ready(function() {
$("#b1").click(function() {
if (count == 5) {
alert("Maximum Number of Input Boxes Added");
} else {
++count;
var tb = "tb" + count;
$(this).before("<div class=\"newTextBox\" id= "+ tb +" >" + 'InputField : <input type="text" name="box[]"></div>');
}
});
$("#b2").click(function() {
if (count == 0) {
alert("No More TextBoxes to Remove");
} else {
$("#tb" + count).remove();
--count;
}
});
$("#submit").click(function(event) {
var string = "#texttb";
var i;
for (i = 1; i <= count; i++) {
if ($('input[type = text]').val() == "") {
event.preventDefault();
break;
}
}
});
});
</script>
<style>
.newTextBox
{
margin: 5px;z
}
</style>
Reason:
you had given id to the div element. so its not get retrive. i had updated the answer with the usage of jquery functions and changed your code for this requirement.
If I understand correctly, your only issue atm is to make sure that the form is not sent if one of the inputs are empty? Seems the solution to your problem is simpler. Simply add required at the end of any input and HTML5 will ensure that the form is not sent if empty. For example:
<input type="text" required />
I am trying to make a little "game" and for some reason, if I try and get the checked of a checkbox, my script will flip out... sometimes it works, sometimes it just stops executing. Is there some sort of an error I missed?
<html>
<head>
<title>Untitled Document</title>
<script>
var check = "showcheck";
var number = 1234;
var lvl = 1;
var oldlvl = 1;
var multiplier = 10000;
var start = 1;
function exefunction() {
document.getElementById("boxv").focus();
if (check == "showcheck") {
document.getElementById("message").innerHTML = "What was the number?";
document.getElementById("num").style.display = "none";
document.getElementById("box").style.display = "inline";
document.getElementById("boxv").focus();
check = "checknum";
}
else if (check == "checknum") {
if (document.getElementById("boxv").value == number) {
document.getElementById("message").innerHTML = "CORRECT!";
document.getElementById("boxv").style.color = "#00DD00";
document.getElementById("boxv").value = number;
document.getElementById("level").innerHTML = "Level: " + lvl;
lvl++;
}
else if (document.getElementById("boxv").value != number) {
document.getElementById("message").innerHTML = "INCORRECT!";
document.getElementById("boxv").style.color = "#DD0000";
document.getElementById("boxv").value = number;
document.getElementById("level").innerHTML = "Level: " + lvl;
if (lvl>1) {lvl--;}
loselife();
}
check = "showmem";
}
else if (check == "showmem") {
if (lvl == oldlvl + 10) {
oldlvl = lvl;
multiplier = multiplier * 10;
document.getElementById("boxv").maxLength = multiplier.toString().length - 1;
}
else if (lvl < oldlvl) {
oldlvl = lvl - 10;
multiplier = multiplier / 10;
document.getElementById("boxv").maxLength = multiplier.toString().length - 1;
}
number = Math.floor(Math.random() * multiplier / 10 * 9) + multiplier / 10;
document.getElementById("boxv").style.color = "#000000";
document.getElementById("boxv").value = "";
document.getElementById("message").innerHTML = "Memorize this number: ";
document.getElementById("num").innerHTML = number;
document.getElementById("num").style.display = "inline";
document.getElementById("box").style.display = "none";
check = "showcheck";
}
}
function loselife(){
var life = 4;
var hearts = "♥ ";
alert(document.getElementById("lifebox").checked);
}
function submitenter() {
var keycode = window.event.keyCode;
if (keycode == 13) {
if (start === 0) {exefunction();}
else {startfunc();}
}
if (keycode < 47 || keycode > 58) {
return false;
}
}
function startfunc() {
document.getElementById("button").innerHTML = '<input name="" type="button" value="OK" onClick="exefunction()"/>';
document.getElementById("level").innerHTML = "Level: " + lvl;
document.getElementById("message").innerHTML = "Memorize this number: ";
document.getElementById("num").style.display = "inline";
document.getElementById("boxv").value = "";
document.getElementById("box").style.display = "none";
if (document.getElementById("lifecheck").checked === true) {
document.getElementById("life").innerHTML = "♥ ♥ ♥ ♥ ♥ ";
}
else if (document.getElementById("lifecheck").checked === false) {
document.getElementById("life").innerHTML = "";
}
if (document.getElementById("timercheck").checked === true) {
document.getElementById("timer").innerHTML = "3:00";
}
else if (document.getElementById("timercheck").checked === false) {
document.getElementById("timer").innerHTML = "";
}
start = 0;
}
function tests() {
alert(lfckv);
}
</script>
<style type="text/css">
#level, #life, #timer{
color: #666;
}
* {
text-align: center;
}
#num {
display: none;
}
#num {
font-size: x-large;
}
#body {
margin-top: 250px;
margin-right: auto;
margin-bottom: 100px;
margin-left: auto;
}
body {
background-color: #6FF;
}
</style></head>
<body onKeyPress="return submitenter()" >
<div id="body">
<span id="level"></span>
<table align="center">
<tr>
<td width="200" height="50" align="center" valign="middle"><span id="message">What level would you like to begin at?</span></td>
<td width="200" height="50" align="center" valign="middle"><span id="num">1234</span><span id="box"><input type="text" id="boxv" maxlength="4" value="1"/></span></td>
</tr>
</table>
<table align="center">
<tr>
<td width="200" id="life"><label><input id="lifecheck" type="checkbox" >Lives</label></td>
<td id="button"><input type="button" value="OK" onClick="startfunc()"/></td>
<td width="200" id="timer"><label><input id="timercheck" type="checkbox" >Timer</label></td>
</tr>
</table>
<input name="" type="button" onClick="tests()" value="tests()">
</div>
</body>
</html>
lifebox isnt defined in the loselife() function. Plus, also check the test() function, that alert() statement has a variable that isnt defined.
If you are using Google chrome (or any other browser that can help you debug), I would suggest you to debug through your lines of code.
I think you're better off using simple equality for checking the state of your checkboxes, because I'm pretty the outcome is not a Boolean.
So it would be something like that :
if (document.getElementById("lifecheck").checked == true) {
or simply
if (document.getElementById("lifecheck").checked) {
instead of
if (document.getElementById("lifecheck").checked === true) {
Ahah! I figured out the problem. Apparently, when I set the visibility of the checkbox to none, it also set the checkvalue to null for some reason. I had expected it to keep the checkvalue, but for some reason it does not.