I'm trying to format the users input in the textarea, where extra spaces and enters are replaced with single spaces fortunately this part works, however only on the 2nd click of the button. I want to know what's wrong and how to fix this:
Here's my code and a fiddle: http://jsfiddle.net/EnXp7/
Html
<textarea type="text" id="address" onfocus="if(this.value===this.defaultValue)this.value=''" onblur="if(this.value==='')this.value=this.defaultValue">
Input Address Here
</textarea>
<input type="button" id="Validate" value="Validate" onClick="valbtn()">
Jquery/Javascript
function valbtn() {
$("#Validate").click(function () {
$('#address').val($('#address').val().replace(/\s+/g, ' '));
});
var x = document.getElementById("address").value;
if (x === "" || x === "Input Address Here") {
alert("No Input");
}
}
Your current function valbtn() gets called on the first click and binds your validation to click again. So you'll have to click again before actually running that validation.
If you keep calling valbtn() onclick, modify the function like that:
function valbtn() {
// Run it instead of binding it to the click event
$('#address').val($('#address').val().replace(/\s+/g,' '));
var x = document.getElementById("address").value;
if (x === "" || x === "Input Address Here") {
alert("No Input");
}
}
Because you are assigning a second click handler inside the click function.
Delete the onClick attribute from you HTML and in Javascript replace your current code with just this:
$("#Validate").click(function () {
$('#address').val($('#address').val().replace(/\s+/g, ' '));
});
Change your code to:
<script type="text/javascript">
$(document).ready(function() {
$("#Validate").click(function() {
$('#address').val($('#address').val().replace(/\s+/g, ' '));
var x = document.getElementById("address").value;
if (x === "" || x === "Input Address Here") {
alert("No Input");
}
});
});
</script>
and totally remove the onclick event in your input:
<input type="button" id="Validate" value="Validate">
With JQuery you dont need that.
You have an action listener in an action listener or in other words you mixed jQuery and JavaScript I suggest you drop the JavaScript call as desribed above and do a pure JQUery action listener which is more clear and easy to use.
It will also take care about browser compatiblity for you.
You should move
$("#Validate").click(function () {
$('#address').val($('#address').val().replace(/\s+/g, ' '));
});
outside of the valbtn function:
$("#Validate").click(function () {
if (valbtn()) {
$('#address').val($('#address').val().replace(/\s+/g, ' '));
}
});
I also made valbtn return boolean indicating if processing is needed or not:
function valbtn() {
var x = $("#address").value;
if (x === "" || x === "Input Address Here") {
alert("No Input");
return false;
}
return true;
}
Updated code: http://jsfiddle.net/EnXp7/1/
Put your jquery script out side valbtn() function. no need create function use only
below code
$("#Validate").click(function () {
$('#address').val($('#address').val().replace(/\s+/g,' '));
});
Related
First time we press keyboard enter key should execute button(id="botonCorregir"). But the second time we press enter key should execute url().
I use cont, for the first time execute one part of the javascript code, and after when de cont value is 1, execute the second part of javascript code.
For some mistake, it doesn´t work.
thanks!
HTML:
<input id="respuestaUsuario"></input>
<button id="botonCorregir">Reply</button>
<a id="enlaceSiguiente" href="nextQuestion.html">Next question</a>
JAVASCRIPT:
<script>
var cont=0;
if(cont==0){
//Should enter the first press of enter
var input = document.getElementById("respuestaUsuario");
console.log('input: ', input)
input.addEventListener("keyup", function(event) {
if (event.keyCode == 13) {
event.preventDefault();
document.getElementById("botonCorregir").click();
}
});
cont++;
}else{
//Should enter the second press of enter
if (event.keyCode == 13) {
event.preventDefault();
document.getElementById("enlaceSiguiente").click();
}
}
</script>
You have a few mistakes in the code.
You are assigning the event based on the value of cont so always will have that functionality. Javascript does not re-interpret the code once the value of cont is changed.
I mean, Javascript check only one time the condition:
if(cont==0){}
This is a solution that works:
var cont=0;
var input = document.getElementById('respuestaUsuario');
input.addEventListener('keyup', function (event) {
event.preventDefault();
if (event.keyCode == 13) {
if(!cont){
alert('uno');
document.getElementById("botonCorregir").click();
cont++;
}else{
document.getElementById("enlaceSiguiente").click();
}
}
});
I guess you were on the right track, but the problem is that your Javascript only gets executed once. So, the else case will never be triggered. I refactored your code to use the check in the event listener:
var cont = 0;
var input = document.getElementById("respuestaUsuario");
input.addEventListener("keyup", function (event) {
if (event.keyCode == 13) {
event.preventDefault();
if (cont == 0) {
cont++;
document.getElementById("botonCorregir").click();
} else {
document.getElementById("enlaceSiguiente").click();
}
}
});
I also created a codepen for you to check out.
I have a form that is split into sections. When the user clicks "continue", I have a jquery script that checks to see if all required fields are filled out. If any aren't, then a box appears with a warning and buttons (They are actually <a> tags) for 'yes' and 'no'. I attach an onclick event to the 'yes' button that triggers a function. The function works, but a # appears in the address bar (website.com/page#), which I'm guessing is because the event.preventDefault(); in my code isn't working.
Here is the function that adds the onclick event:
function checkSection (event, check, goTo) {
event.preventDefault();
var emptyFields = "0";
$("#ia"+check+"Div .check").each(function() {
var val = $(this).val();
if (val == "") {
emptyFields++;
}
});
if (emptyFields >= 1) {
$(".mask").show();
$("#warningBox").show();
$(document).on("click", "#yesBtn", function() {
var x = window['save'+check];
x(event, goTo);
$("#warningBox").hide();
$(".mask").hide();
});
} else {
var x = window['save'+check];
x(event, goTo);
$("#warningBox").hide();
}
}
Here is the tag I am adding the event to:
<div class="medBtn short">
<div class="btnTbl">
Yes
</div>
</div>
The function I end up calling is like this:
function saveContact(event, val) {
event.preventDefault();
//Do Stuff - This is the function where event.preventDefault(); isn't working
}
Like I said, the function still works, so if it's not something I can get around, that is fine. I just don't like having a # in the address bar.
The event object doesn't exist until the event occurs
You prevent default inside the actual event handler
$(document).on("click", "#yesBtn", function(event) {
event.preventDefault();
....
})
http://jsfiddle.net/B9Fub/
<tr class="fis">
Test: <input type="text" name="test" id="test" value="Test">
<tr class="fis">
Empty: <input type="text" name="empty" id="empty">
<input type="button" value="find" id="find">
$('#find').click(function() {
alert('wont work if any other fields are filled other than TEST');
});
$('#test').change(function() {
// needs to fill the form for other functionality
$('#empty').val('empty');
alert('change');
});
So here I have fields that are filled when the first input is 'changed'
But I don't want it to run [change] if they input in the first field and click the 'find' button.
I was wondering if there was a way to do this. From what I found, 'change' happens before the 'find' button if you click on it.
I've tried changing 'change' to 'focus' and give it to the other field so the first field has no event handlers, but that may give me trouble further down the way.
I need the fields to be filled but I don't want them filled if the user clicks the find button.
The mousedown event fires before the change event, so by using that and jQuery's data() method you can set a flag to see if the activeElement is in fact #test when the find button is clicked, and if so don't set the value :
$('#find').on('mousedown', function() {
$('#test').data('flag', document.activeElement.id === 'test');
});
$('#test').on('change', function() {
if ( ! $(this).data('flag') ) $('#empty').val('empty');
});
FIDDLE
Still, not sure what you want. Maybe this will help.
var frm = $('form')[0]; //assuming you have one form on that page
var fnd = $('#find');
fnd.click(function(){
var te = 0, fe = 0;
if(frm.elements[0].value !== '')te = 1;
for(var i=1,l=frm.length; i<l; i++){
if(frm.elements[i].value !== '')fe = 1;
}
if(fe === 1){
return false;
}
else{
// do your thing here
return true; // some editors show an error if you don't always return a value
}
});
$('#test').change(function(){
if(fnd.val() !== ''){
return false;
}
else{
// do your thing here
return true;
}
});
I've found the answer. Using e.stopPropagation(); on $('#find') allowed me to stop the .change() from occurring
I'm can't figure out a way of displaying a message if a specific word is inputed into an input box. I'm basically trying to get javascript to display a message if a date, such as '01/07/2013', is inputed into the input box.
Here is my html
<p>Arrival Date</p> <input type="text" id="datepicker" id="food" name="arrival_date" >
I'm using a query data picker to select the date.
You can insert code in attribute onchange
onchange="if(this.value == 'someValue') alert('...');"
Or create new function
function change(element){
if(element.value == 'someValue'){
alert('...');
}
}
And add attribute
onchange="change(this);"
Or add event
var el = document.getElementById('input-id');
el.onchange = function(){
change(el); // if 'el' doesn't work, use 'this' instead
}
I'm not sure if it works, but it should :)
Use .val() to get the value of the input and compare it with a string
var str = $('#datapicker').val(), // jQuery
// str = document.getDocumentByI('datapicker').value ( vanilla js)
strToCompare = '01/07/2013';
if( str === strToCompare) {
// do something
}
And encase this in either change or any keyup event to invoke it..
$('#datepicker').change(function() {
// code goes here
});
Update
Try the code below.
$(function () {
var $datepicker = $('#datepicker');
$datepicker.datepicker();
$datepicker.on('change', function () {
var str = $datepicker.val(),
strToCompare = '07/19/2013';
if (str === strToCompare) {
console.log('Strings match')
}
else {
console.log('boom !!')
}
});
});
Check Fiddle
Your input has 2 ids. You need to remove id="food". Then the following should work with IE >= 9:
document.getElementById('datepicker').addEventListener(
'input',
function(event) {
if (event.target.value.match(/^\d+\/\d+\/\d+$/))
console.log("Hello");
}, false);
I have a javascript code that works by removing the first and the last line of it.
Please take a look at JSFiddle
for people who wants to see it in here, here is my html:
<input id="search" onclick="search()" type="button" value="Search"/>
my javascript :
function search() {
var search = document.getElementById('search');
var int = setInterval(function() {
if (search.value.length == 6)
search.value = 'Searchi';
else if (search.value.length == 7)
search.value = 'Searchin';
else if (search.value.length == 8)
search.value = 'Searching';
else {
search.value= 'Search';
}
//clearInterval( int ); // at some point, clear the setInterval
}, 500);
}
I want the function to work only when I click the button.
You've selected jQuery in jsfiddle.net which by default causes the site to wrap your whole code in a document.ready handler.
The result is that your search function becomes a local function within that wrapper, and not a global variable as required by a DOM0 onclick handler.
Set the jsfiddle options to "no wrap (body)" and "No-Library (pure js)" to turn off that functionality.