Javascript document.getElementById set input - javascript

I got some input validator, that checks if user e-mail and username not registered on website. My code looke like that:
Javascript:
$(document).ready(function()
{
$('#email').blur(function(event) {
$.get(BaseUrl + 'auth/email/check/' + $(this).val(), function(data)
{
if (data == 1) {
$('input#email').removeClass('valid');
$('input#email').addClass('error');
document.getElementById('div-error').style.display = "block";
} else {
document.getElementById('div-error').style.display = "none";
}
});
});
$('#username').blur(function(event) {
$.get(BaseUrl + 'auth/username/check/' + $(this).val(), function(data)
{
if (data == 1) {
$('input#username').removeClass('valid');
$('input#username').addClass('error');
document.getElementById('div-error').style.display = "block";
} else {
document.getElementById('div-error').style.display = "none";
}
});
});
});
DIV code after username input:
<div id="div-error" style="display: none;">username has alerdy registered</div>
DIV code after e-mail input:
<div id="div-error" style="display: none;">email already registered</div>
But then username is not-registered and email already registered i'm getting error on all this 2 inputs... How can i set document.getElementById for special inputs?

Your error-divs got the same id. An ID in HTML must be unique.
Try giving these elements classes like
<div class="div-error" id="div-error-username" style="display: none;">...</div>
<div class="div-error" id="div-error-email" style="display: none;">...</div>

Related

How to show a response when filtering through a list of elements using javascript

Hello I am creating an FAQ page that has to be filtered using javascript as below
Credit : https://makitweb.com/jquery-search-text-in-the-element-with-contains-selector/
$(document).ready(function () {
$('#filter').keyup(function () {
// Search text
var text = $(this).val().toLowerCase();
var error = document.getElementById("error");
// Hide all content class element
$('.mobrog-ux-text').hide();
// Search
$('.mobrog-ux-text').each(function () {
if ($(this).text().toLowerCase().indexOf("" + text + "") != -1) {
$(this).closest('.mobrog-ux-text').show();
setTimeout(
function () {
var x = document.getElementById("myDIV");
x.style.display = "none";
}, 4000);
error.style.display = "none";
}
else if($(this).text().toLowerCase().indexOf("" + text + "") == 0) {
error.style.display = "block";
}
});
});
});
<form align="center">
<input id="filter" onkeydown="keydownFunction()" oninput="keyPress(this.value)" class="searchfield" type="text"
name="search" placeholder="Search the help center">
</form>
<div style="color: white;padding : 10px" align="center"></div>
</div>
<div class="content2">
<h2>Frequently asked questions</h2>
<div id"pag"="id" pag""="pag" ""></div>
<div align="center" class="col-10">
<div class="mobrog-tab-container maxwidth">
<div id="myDIV" class="loader"></div>
<div class="error" id="error"> No result found!!</div>
<div id="results" class="mobrog-ux-vertical-tabs">
<div id="tar" class="mobrog-tabs">
<button data-tab="tab1" class="active">sample tab button?<span></span></button>
<button class="empty"></button>
</div>
<div class="mobrog-maincontent">
<div data-tab="tab1" class="mobrog-tabcontent active">
<div class="mobrog-ux-text">
<button class="mobrog-accordion">sample button</button>
<div class="mobrog-panel">
<p>
sample text
</p>
</div>
</div>
Which works, but then I am trying to show a message when the filtered word is not found within the list of DIVS I'm searching through on my FAQ page
I tried the below with
else if ($(this).text().toLowerCase().indexOf("" + text + "") == 0) {
//error message display
}
But then it does not work
(e.g when I type in a word which does not exist within my FAQ I want to display an error message which is in a div) and vice versa when the word is found in my FAQ page)
like the way its been used in the method of RegExp
Live search on an Div with input filter
at the moment when I type in available and unavailable words the error message appears
Please how do I effectively display a message when a filtered word is found or not found
Thanks
Expanding on my comment, this is an example of how you could implement something like this.
To reiterate - the main problem was that the error was being shown if any result didn't match instead of showing if none match
To fix that, we can add a variable outside the loop to determine if any result was matched
$(document)
.ready(function () {
$('#filter')
.keyup(function () {
// Search text
var text = $(this).val().toLowerCase();
var error = document.getElementById("error");
// storing this in a variable will reduce how many times you call the function
var $ux_texts = $('.mobrog-ux-text');
// Hide all content class element
$ux_texts.hide();
// variable to update if any match is found
var has_match = false;
// Search
$ux_texts
.each(function () {
var $this = $(this);
if ($this.text().toLowerCase().indexOf("" + text + "") === -1) {
// flip the logic so we can return early - makes for cleaner code
return;
}
$this.closest('.mobrog-ux-text').show();
setTimeout(function () {
var x = document.getElementById("myDIV");
x.style.display = "none";
}, 4000);
has_match = true;
});
// error handling
if (has_match) {
error.style.display = "none";
} else {
error.style.display = "block";
}
});
});

redirect to another page if (text area (input) === "something") when a button is clicked

This is the way I approached it. Please help:
Search
<script type="text/javascript">
var criteria = document.getElementById("search").val().toLowerCase();
if (criteria == "crosshatching") {
document.getElementById("searchBtn").onclick = function() {
window.location.href = "https://www.youtube.com/watch?v=117AN3MQuVs";
}
}
</script>
There was no scope for the variable criteria inside the function.
Also .val() is for jQuery, instead use Javascript's .value.
I've modified your code.
Please check the working code below :
document.getElementById("searchBtn").onclick = function() {
var criteria = document.getElementById("search").value.toLowerCase();
if (criteria == "crosshatching") {
alert("Matching");
window.location.href = "https://www.youtube.com/watch?v=117AN3MQuVs";
} else {
alert("NOT Matching");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="search" id="search"></textarea>
<button id="searchBtn">Search</button>
You need to check the value of your input inside the event handler. In addition, as pointed out in the comments, use value instead of val().
document.getElementById('searchBtn').addEventListener('click', function() {
var criteria = document.getElementById('search').value.toLowerCase();
if (criteria === "crosshatching") {
console.log('You would be redirected here!')
location.href = 'https://www.youtube.com/watch?v=117AN3MQuVs'
} else {
console.log('No redirect. You wrote: ' + criteria)
}
})
<input id="search" type="text"/>
<button id="searchBtn">Search</button>

Jquery Error validation insert div using after() but cannot remove

I want to show error validation messages next to the textbox. For that, I have used after() function and inserted a div. But the div gets appended again and again whenever the field is invalid. I just want it once. Can anybody help me with it?
Here's my code:
$(document).ready(function()
{
$("#name").blur(function()
{
var name = $("#name").val();
var txt= /^[A-Za-z\s]+$/i ;
if((txt.test(name) != true))
{
$("#name").after('<div id="one" style="color:#00aaff;">Invalid Name</div>');
$("#one").empty();
}
else
{
$("#one").remove();
}
});
});
You could use HTML 5 field's validity which is the standard.
<input type="text" pattern="[a-zA-Z]+"
oninvalid="setCustomValidity('Your error message here')"
onchange="setCustomValidity('')" />
You should use additional variable to store your state. Try this logic.
$(document).ready(function() {
var flag = false;
$("#name").blur(function() {
var name = $("#name").val();
var txt = /^[A-Za-z\s]+$/i;
if (!txt.test(name) && !flag) {
$("#name").after('<div id="one" style="color:#00aaff;">Invalid Name</div>');
flag = true;
}
else if (flag && txt.test(name)) {
flag = false
$("#one").remove();
}
});
});

jquery show alert on click

I have a simple log in at the top of my page, when the user enters their id thats on my json file their name appears in a welcome alert(the welcome alert is avaiable on ready and the name appears inside when the user logs in). I want the alert to be hidden but when the users enters their code (there is no username just a code) this alert appears with the name.
Here is the log in text and button:
<div class="alert alert-info"><input type="text" id="userName" value> <button type="button" id="loginbtn" class="btn btn-primary btn-md">Login</button></div>
Here is the alert:
<div class="alert alert-success" id="loginalert"<strong>Welcome</strong></div>
and here is the js getting the corresponding name to appear:
$(document).ready(function() {
$("#loginbtn").click(function(event){
//console.log("clicked login");
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
//console.log(id);
for (var i=0; i<jd.user.length; i++) {
if (jd.user[i].ID == id) {
$('#loginalert').html('<p> Welcome: ' + jd.user[i].name + '</p>');
}
}
});
}); });
the json file includes the users id (which is the code for now) : 001
and their name
when the code is entered to the login text box their name appears on the page to indicate what user has logged in
I also wanted to know.. if there was no corresponding id to the four i have included in my json is there any way to get this alert to appear instead of the login alert, this would be like a you have entered an invalid code -
<div class="alert alert-danger"> <strong>Danger!</strong> Indicates dangerous or potentially negative action.</div>
(also to be hidden on page load/ready)
Can anyone help out guys please?
Kind regards
Try this: I have modified your script.
$(document).ready(function() {
//Hide alert when page loads
$("#loginalert").hide();
$("#loginbtn").click(function(event){
//console.log("clicked login");
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
//console.log(id);
for (var i=0; i<jd.user.length; i++) {
if (jd.user[i].ID == id) {
$('#loginalert').html('<p> Welcome: ' + jd.user[i].name + '</p>');
//show the alert after loading the information
$("#loginalert").stop().fadeIn('slow').animate({ opacity: 1.0 }, 3000).fadeOut('slow', function () {
$('#contact').fadeIn('slow');
});
}
}
});
});
});
For Error Message try:
Modify your div to this,
<div class="alert alert-danger" id="ErrorMessageAlert"> <strong>Danger!</strong> Indicates dangerous or potentially negative action.</div>
Thereafter modify your scripts again to this:
$(document).ready(function() {
//Hide alert when page loads
$("#loginalert").hide();
$("#ErrorMessageAlert").hide();
$("#loginbtn").click(function(event){
//console.log("clicked login");
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
//console.log(id);
for (var i=0; i<jd.user.length; i++) {
if (jd.user[i].ID == id) {
$('#loginalert').html('<p> Welcome: ' + jd.user[i].name + '</p>');
//show the alert after loading the information
$("#loginalert").show();
}else
{
$("#ErrorMessageAlert").show();
}
);
}
}
});
});
});
You can make your both alert forms hidden by default by adding hidden class and then through query show()-http://api.jquery.com/show/ display needed one
<style>
.hidden{
display:none;
}
</style>
<div class="alert alert-info hidden"><input type="text" id="userName" value> <button type="button" id="loginbtn" class="btn btn-primary btn-md">Login</button></div>
<div class="alert alert-danger hidden"> <strong>Danger!</strong> Indicates dangerous or potentially negative action.</div>
<script>
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
// Defined to keep if match found in loop
var matchFound = false;
for (var i=0; i<jd.user.length; i++) {
if (jd.user[i].ID == id) {
$('#loginalert').html('<p> Welcome: ' + jd.user[i].name + '</p>');
// Show Welcome alert
$(".alert-info").show();
matchFound = true;
break;
}
}
// which means no match found and matchFound is not equal to true
if( !matchFound ){
// Show Error alert
$(".alert-danger").show();
}
});
</script>

validate dynamically created div depending on condition

I have code that allows a user to pick between 2 options of a person TYPEA and TYPEB.
SELECT PERSON - { TYPEA, TYPEB }
Depending on the choice, it shows:
TYPEA - { TYPEA WITH ID, TYPEA WITHOUT ID }
TYPEB - { TYPEB WITH ID, TYPEB WITHOUT ID }
It is working with this:
html:
<div id="person-A-withID" class="persons" style="display:none"></div>
<div id="person-A-withoutID" class="persons" style="display:none"></div>
<div id="person-B-withID" class="persons" style="display:none"></div>
<div id="person-B-withoutID" class="persons" style="display:none"></div>
jQuery:
$(function () {
$('#has_id').show();
$('#select_person').change(function () {
$('.persons').hide();
if ($('#select_person').val() == 'typeA') {
$("#has_id").html('');
$("<option/>").val('0').text('--Choose Type A--').appendTo("#has_id");
$("<option/>").val('person-A-withID').text('person-A-withID').appendTo("#has_id");
$("<option/>").val('person-A-withoutID').text('person-A-withoutID').appendTo("#has_id");
}
if ($('#select_person').val() == 'typeB') {
$("#has_id").html('');
$("<option/>").val('0').text('--Choose Type B--').appendTo("#has_id");
$("<option/>").val('person-B-withID').text('person-B-withID').appendTo("#has_id");
$("<option/>").val('person-B-withoutID').text('person-B-withoutID').appendTo("#has_id");
}
});
$('#has_id').change(function () {
$('.persons').hide();
$('#' + $(this).val()).show();
});
});
I have a function to validate if the value is empty or equals 0 with the following code:
function validate(id, msg) {
//search object
var obj = $('#' + id);
if(obj.val() == '0' || obj.val() == ''){
//append error to particular div called #id__field_box
$("#" + id + "_field_box .form-error").html(msg)
return true;
}
return false;
}
and I call it inside a validate function like this:
var validation = function(){
var err = 0;
err += validate('select_person', "select person.");
//err += validate($('#select_person:first-child').attr('has_id'), "Select wether it has ID or not.");
//err += validate('has_id', "Select wether it has ID or not.");
if(err == 0){
//continue
}else{
//stop
}
};
Now, the problem is that I cannot validate the has_id part, I am only able to validate the first one. How can I use it to search for has_id?
here is a fiddle, please take a look at it
In your example, there isn't an element with the id of 'selector_persona'. This prevents your second validate function from working. By passing it the id of what you're trying to validate ('has_id'), it references the object and checks to make sure it has a value.
Choose a person, leave the second select as "--Choose Type A--" and click ok. It returns your error.
http://jsfiddle.net/zyglobe/LEfbX/131/
var validation = function(){
var err = 0;
err += validate('select_person', "select person.");
err += validate('has_id', "Select whether it has an ID or not.");
if(err == 0){
alert('continue');
} else{
alert('error: ');
}
};
You may also check this part:
$('#select_person:first-child').attr('has_id')
You're trying to find an attribute with the name has_id, which would work for something like this:
<select has_id="some_value" />
I think you mean to select the attr('id') which will return the value of 'has_id':
<select id="has_id" />

Categories