how to check properly formatted email id - javascript

<script>
window.onload = function()
{
document.getElementById('btn').disabled=true;
function bar()
{
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var d=document.getElementById('uid').value;
if( re.test(d))
document.getElementById('btn').disabled=false;
}
};
</script>
<button type="button" id="btn" >Log-in</button>
<label for="uid">User Id</label><input type="text" name="uid" id="uid" onKeyUp="return bar()" />
I am trying to check whether the email id entered in the textbox uid is properly formatted or not and if the email id given matches the expression it will simply enable the btn button. when i execute the following nothing happen the button stays disabled if even the email id is formatted properly. HELP!

You have a scope issue. The bar() function is defined within the window.onload function, and therefore is not accessible from where you try to call it (the inline onkeyup handler).
Move the function into the global scope:
function bar() {
...
}
window.onload = function () {
document.getElementById('btn').disabled = true;
};
Or better still, attach the event inside the window.onload and remove the inline onkeyup completely.
DEMO
function bar() {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var d = document.getElementById('uid').value;
document.getElementById('btn').disabled = !re.test(d);
}
window.onload = function () {
var btn = document.getElementById('btn').disabled = true;
document.getElementById("uid").onkeyup = bar;
};
Using this way, bar can be defined either in the onload or in the global scope, both will work. Also, I changed the logic in bar(). It will now re-disable if you type a valid email, then make it invalid.

Related

Unable to get user input from input field and assign it to another div's innerHTML

I know that this question sounds silly but i am curious why i can avoid this problem in JavaScript. Now in the code below i have given :
var btn=document.getElementById("btn");
btn.onclick = function get() {
var x = document.getElementById("text").value; // --> HERE
document.getElementById("para").innerHTML = x;
};
get();
<input type="text" id="text" value="">
<input type="submit" value="submit" id="btn">
<p id="para"></p>
Now when i assign the variable x inside the function ,after the ("text") i get the .nodeValue instead of getting the .value. Is that a problem with my code editor or i have an error, because every time i put a name inside the input field it shows the result inside the paragraph it appears and fast also disappears
So I see 2 problems here:
You didn`t close your script tag.
You are calling get(); but the function does not exist in that scope but is only assigned in the onclick event.
This should do the trick:
var btn=document.getElementById("btn");
btn.onclick = function get() {
var x = document.getElementById("text").value;
document.getElementById("para").innerHTML = x;
};
<input type="text" id="text" value="HELLO">
<input type="submit" value="submit" id="btn">
<p id="para"></p>
I have preset the value to "HELLO", but you can change it as you want, and it will deliver the value requested when clicking on the button.
I think your only problem may have been how you were declaring the event listener, I declared it as an event listener on the button listening to the 'click' event.
I also edited 'x' to be 'userInput' so it is more clear what it is trying to achieve.
var btn = document.getElementById("btn");
btn.addEventListener('click', function () {
var userInput = document.getElementById("text").value;
document.getElementById("para").innerHTML = userInput;
});
var btn=document.getElementById("btn");
btn.onclick = function () {
var x = document.getElementById("text").value; // --> HERE
document.getElementById("para").innerHTML = x;
};
btn.onclick()
<input type="text" id="text" value="hello">
<input type="submit" value="submit" id="btn">
<p id="para"></p>
This is a working example of what you are trying to do. You can't declare a function in that context as it's anonymous. My example works perfectly, but you should do something more like
function get() {
//Do something
}
btn.onclick = get;
get();
I am not sure whether this will solve or not. However, I suggest you by giving an onclick event inside the input tag.
<input type="submit" value="submit" id="btn" onclick="get()">
<script>
function get() {
var x = document.getElementById("text").value;
document.getElementById("para").innerHTML = x;
}
</script>`

Javascript function does not work on onclick of checkbox

I try to call a Javascript function through an onclick attribute of a checkbox.
The js should show another checkbox if the first one is checked etc.
Now the function isnt working. I tried to use just an alert() for testing without any result...
Fitness:<input type="checkbox" id="fitnessCheck" onclick="checkFunction()">
Beauty:<input type="checkbox" id="beautyCheck">
Streetwear:<input type="checkbox" id="streetwearCheck">
Luxus:<input type="checkbox" id="luxusCheck" onClick="checkFunction()">
Datenschutz: <input style="display:none" type="checkbox" id="datenschutzCheck">
<script>
checkFunction(){
//get Checkboxes
var fitnessCheckbox = document.getElementById("fitnessCheck");
var beautyCheckbox = document.getElementById("beautyCheck");
var streetwearCheckbox = document.getElementById("streetwearCheck");
var luxusCheckbox = document.getElementById("luxusCheck");
var datenschutzCheckbox = document.getElementById("datenschutzCheck");
if(fitnessCheckbox.checked == true || beautyCheckbox.checked == true || streetwearCheckbox.checked == true || luxusCheckbox.checked == true){
datenschutzCheckbox.style.display ="block";
}
}</script>
You have to declare the function checkFunction().
You can do it in many ways such as:
function checkFunction() {
// code here
}
or
var checkFunction = function() {
// code here
}
etc, depending on how you are going to use the function.
This is how to define a function in JavaScript.
Correct your function as below;
function checkFunction(){
}
Alternatively, remove the onclick attribute from HTML and put it in the JavaScript as defined below
var fitnessCheckbox = document.getElementById("fitnessCheck");
fitnessCheckbox.onclick() = function() {
// access properties using this keyword
if ( this.checked ) {
// if checked ...
alert( this.value );
} else {
// if not checked ...
}

event.preventDefault prevents ajax call

I have been trying to get an ajax call to work inside a function triggered by an onclick event. When I use event.preventDefault the page is not reloaded but the ajax call does not work, no data is added to my database. When I comment out that line the page is reloaded but everything else works.
function clickFunction(elem) {
var var1 = elem.id;
var var2 = var1.split("_");
// elem.preventDefault();
if (var2[0] == "Add") {
if (var2[1] == "Calls") {
console.log("Calls");
console.log(var1);
event.preventDefault();
var data = $(this).serialize();
$.post('progressSheetDynamic', data).done(function (response){
$(".1").html(parseInt($('.1').html(), 10)+1);
Calls.update(50);
});
}
}
}
Html code
<form action="{{ route("progressSheetDynamic") }}" method="post" id= {{ $addID }}>
<input name="increment" value="increment" type="hidden"> </input>
<input type="hidden" name="id" value= {{$activities}} >
<button type="submit" class="styleHover styleButton" onclick="clickFunction(this)" id= {{ 'Add_'.$newText }}> + </button>
</form>
I have checked the logs and the function is going into the if statement. I have also tried using preventDefault on the button click event, by doing elem.preventDefault(); but this does not work. Neither does using return false.
The issue seems to be with this line:
var data = $(this).serialize();
It should be this instead:
var data = $(elem.form).serialize();
The this value in your function will be a reference to the window object, whereas elem is the button so elem.form will be the form to serialize (assuming that's the data you wanted).
And as noted in the comments, event is only defined as a global variable in some browsers, so you need to pass event in the attribute and receive it in the function to be safe.
Attribute:
onclick="clickFunction(this, event)"
Function:
function clickFunction(elem, event) {
// ...
}
Note that IE8 and lower do not have event.preventDefault(), but you can set event.returnValue = false instead.
event will not be defined because yuo haven't passed it. You're passing the button through with onclick="clickFunction(this).
Change it to onclick="clickFunction(event)".
Then change the function declaration:
function clickFunction(event) {
console.log(event)
...
}
If you want both the button and the event, look at what I have:
<button type="submit" class="styleHover styleButton" onclick="clickFunction(event, this);" />
<script>
function clickFunction(event, elem) {
console.log(event);
console.log(elem);
event.preventDefault();
}
</script>
Elem will be referencing the button when you pass this to clickFunction(this)
But button does not have a preventDefault() function, thus you will get a Uncaught TypeError: elem.preventDefault is not a function
Second, $(this) is referencing window, which should be $(elem.form) instead.
Below is how I fixed your original problem without changing your structure.
Html: (Not passing this in clickFunction)
<button type="submit" class="styleHover styleButton" onclick="clickFunction()" id= {{ 'Add_'.$newText }}> + </button>
Javascript: (use event.target for elem, $(elem.form) for $(this) )
function clickFunction(event) {
var elem = event.target; // event.target will be equivalent to your elem
var var1 = elem.id;
var var2 = var1.split("_");
event.preventDefault();
if (var2[0] == "Add") {
if (var2[1] == "Calls") {
console.log("Calls");
console.log(var1);
event.preventDefault();
var data = $(elem.form).serialize(); // should be elem.form here to get correct data
$.post('progressSheetDynamic', data).done(function (response){
$(".1").html(parseInt($('.1').html(), 10)+1);
Calls.update(50);
});
}
}
}

JS: why this object property won't work and it only works if I put it inside one of the methods as a variable?

I have this form that replaces some text input box for the content of that input box. It does work as intended, but only if I create a variable inside the method, and not outside it as a property of the object.
So this is how I would like it to be (nombre as a property of the object reservasAPP):
<form id="form1" action="">
<div class="row col-md-5">
Horario: 09 horas
<span id="horario09"><input type="text" id="h09"></span>
<button class="btn btn-primary btn-xs" onclick="return reservas.guardarReserva();">Reservar</button>
<button class="btn btn-danger btn-xs" onclick="return reservas.cancelarReserva();">Cancelar</button>
</div>
</form>
var reservasAPP = {
nombre: $('#h09').val(),
guardarReserva:function(){
var reservaConfirmada = $('#horario09').html('--> '+this.nombre);
return false;
},
cancelarReserva:function(){
var reservaCancelada = $('#horario09').html("<input type=\"text\" id=\"h09\">");
return false;
}
}
window.reservas = reservasAPP;
But this is how it actually works:
var reservasAPP = {
guardarReserva:function(){
var nombre = $('#h09').val();
var reservaConfirmada = $('#horario09').html('--> '+nombre);
return false;
},
cancelarReserva:function(){
var reservaCancelada = $('#horario09').html("<input type=\"text\" id=\"h09\">");
return false;
}
}
window.reservas = reservasAPP;
The HTML form is exactly the same.
Why it doesn't work as a property?
If I try: console.log(this.nombre); I get nothing.
Your desired code will never work how you want it to, given upon object literal creation(what you're doing), the return value of the .val() call is set as the value. This only happens once, hence further calls will always have the same value.
If you want the nombre property to evaluate to the value you wish, every time you access it, the .val() call must be shoved inside of a method with that property name, with the return value of the call:
var reservasAPP = {
nombre: function () {
return $('#h09').val();
},
guardarReserva:function(){
var reservaConfirmada = $('#horario09').html('--> '+this.nombre());
return false;
},
cancelarReserva:function(){
var reservaCancelada = $('#horario09').html("<input type=\"text\" id=\"h09\">");
return false;
}
}
Lastly, depending on where your code is(since you don't specify, I don't know), the reason your console.log() call doesn't log anything is likely because you're calling the val code before the DOM has loaded, meaning it isn't there yet. This thought is based solely on the fact that I see no $(document).ready() call in your code.
It is working, but maybe is not what you are expecting.
Here is JSFidle to check it.
JSFiddle
Check the console.
The problem is, when you create the object reservasAPP, you assign the field value to 'nombre'.
So if you change the input of the field and press 'Reservar' it will keep the previous value.
If you want to store in 'nombre' the current value of the field, you should apply a function like:
nombre: function(){
return ($('#h09').val() || '');
}
And do not forget that now nombre is a function and should be called with () at the end.
guardarReserva:function(){
var reservaConfirmada = $('#horario09').html('--> '+this.nombre());
return false;
}
And finally:
console.log(window.reservas.nombre())

Change and Input events

So I'm unable to register for change or input events that allow me to grab the data that was just changed and apply it somewhere else...
document.getElementById("fI").addEventListener("input", blabla);
function blabla() {
var something = document.getElementById("fI").innerHTML;
document.getElementById("example2").innerHTML = something+" continue the rest of the script here";
}
This code doesn't execute and I can't figure out why from the documentation...
Edit:
This is the only HTML on the page, I'm debugging this right now
<textarea id="fI"></textarea>
<button type="button" id='pressMe'>Press Me</button>
<textarea id="example2"></textarea>
I've also used <p> for the recipient of the changed innerHTML
I've tested this code all on it's own, just like this, and it didn't work, however I'm trying to connect the code to this event listener too
document.getElementById("pressMe").addEventListener("click",doSomething);
function doSomething () {
var something = prompt("Please enter something", "something");
if (something !== null) {
document.getElementById("fI").innerHTML = something;
}
}
Use .value to get/set the contents of a textarea element. You were using .innerHTML.
document.getElementById("pressMe").addEventListener("click", doSomething);
function doSomething() {
var something = prompt("Please enter something", "something");
if (something !== null) {
document.getElementById("fI").value = something;
}
}
document.getElementById("fI").addEventListener("input", blabla);
function blabla() {
var something = document.getElementById("fI").value;
document.getElementById("example2").value = something;
}
<textarea id="fI"></textarea>
<button type="button" id='pressMe'>Press Me</button>
<textarea id="example2"></textarea>
you are not retrieving the value of your textarea correctly. you should be using .value instead of .innerHTML
var something = document.getElementById("fI").value;
http://jsfiddle.net/6pL8qony/

Categories

Resources