not sure why the second if else condition is not working - javascript

enter image description hereScenario: Even if i select the image and date the code is not working.
Also if i select year 2020 n say am selecting the first image it should go the specified redirecting page... when i select the year 2021 n the same first image it should go to another page...If i use the else if giving the condition "2020 n img" it is not working.
Code: "For submit Button"
<p align=center>
<input type="submit" value="submit" id="button">
</p>
<script type="text/javascript">
let _img = document.getElementById("img");
let _img1 = document.getElementById("img1");
let _img2 = document.getElementById("img2");
let _picker = document.getElementById("picker");
let _btn = document.getElementById("button");
let isImgClicked = false;
let isDatePicked = false;
_img.addEventListener("click", function(){
isImgClicked = true;
});
_img1.addEventListener("click", function(){
isImgClicked = true;
});
_img2.addEventListener("click", function(){
isImgClicked = true;
});
_picker.addEventListener("click", function(){
isDatePicked = true;
});
_btn.addEventListener("click", function(){
if(!isImgClicked || !isDatePicked)
{
alert("select the Year and Click the car image");
}
else
{
if((isImgClicked == "img") && (isDatePicked == "2020"))
{
window.location.replace("sample.html");
}
else if((isImgClicked == "img") && (isDatePicked == "2019"))
{
window.location.replace("sample1.html");
}
else
{
if((isImgClicked == "img1") && (isDatePicked == "2019"))
{
window.location.replace("sample2.html");
}
else if((isImgClicked == "img1") && (isDatePicked == "2020"))
{
window.location.replace("sample3.html");
}
else
{
alert("!!!!")
}
}
}
});
</script>
For images:
<div class="swiper-container">
<div class="swiper-wrapper">
<form>
<div id="img" class="swiper-slide"
style="background-image: url(./img/nature.png)">
<b>nature</b>
</div>
</form>
<div id="img1" class="swiper-slide"
style="background-image: url(./img/nature1.png)">
<b>nature1</b>
</div>
<div id="img2 "class="swiper-slide"
style="background-image: url(./img/nature2.png)">
<b>nature2</b>
</div>
</div>
<!-- Add Pagination -->
<div class="swiper-pagination"></div>
</div>
Date Picker:
<div id="picker">
<p align="center">
<b>Year:</b> <input type="text" id="datepicker">
</p>
</div>
<script>
$(function() {
$('#datepicker').datepicker({
changeYear: true,
showButtonPanel: true,
dateFormat: 'yy',
onClose: function(dateText, inst) {
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, 1));
}
});
$("#datepicker").focus(function () {
$(".ui-datepicker-month").hide();
$(".ui-datepicker-calendar").hide();
});
});
</script>[enter image description here][2]

Well, I think I have coded pretty much for you. There were lots of errors in there.
First of all, you simply could not check boolean with string like you did or I did.
Boolean only have true or false. This line of code was just so dummy mistake as I explained:
isImgClicked.equals("img1") // This will always be false as isImgClicked is boolean only
Now, here is what I have done, keeping that you have already embedded jquery in your page. Feel free to ask, if there is any doubt.
let _img = document.getElementById("img");
let _img1 = document.getElementById("img1");
let _img2 = document.getElementById("img2");
let _btn = document.getElementById("button");
let isImgClicked = false;
let isDatePicked = false;
/* If any event is clicked!!!! */
$(document).on('click', function(e){
clickId = e.target.id; // Get id of clicked element
pickedDate = $('#datepicker').val(); // Get value of date picked
// If picked date value is not null, means date is picked
if(pickedDate.length > 0){
isDatePicked = true;
}
if(clickId == 'img' || clickId == 'img1' || clickId == 'img2'){
isImgClicked = true;
selectedImg = clickId; // Get id of selected image
}
if(clickId == 'button')
{
if(!isImgClicked)
{
alert("select the Year and Click the car image");
}
else
{
if((selectedImg == "img") && (pickedDate == "2020"))
window.location.replace("sample.html");
else if((selectedImg == "img") && (pickedDate == "2019"))
window.location.replace("sample1.html");
else if((selectedImg == "img1") && (pickedDate == "2019"))
window.location.replace("sample2.html");
else if((selectedImg == "img1") && (pickedDate == "2020"))
window.location.replace("sample3.html");
else
alert("!!!!")
}
}
});
You should be able to fix any other problem by now. There may be div id's mix match to look upto. You could replace your js code for submit button with this one and check for the errors. Thank you!!!

Did you add the jquery and jqueryui libraries? If not, copy the following lines at the beginning, e.g. head section, of your code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
Moreover, correct this line:
<div id="img2 "class="swiper-slide"
with this line:
<div id="img2"class="swiper-slide"

Related

auto tabbing on the first textbox isnt working

the following is code is used to create a credit card. My only promblem is that auto tabbing doesnt work for my textbox with the id of card.i have a external file for the auto tabbing and i have attached the code under the html code.Thanks in advance.
<head>
<title>Credit Card</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script>
<script src="jquery.autotab.js"></script>
<script src="Jstepper.js"></script>
</head>
</body oncopy="return false" oncut="return false" onpaste="return false">
<style>
#Month{
width: 20px;
}
#Year{
width: 40px;
}
#Cvc{
width: 30px;
}
</style>
<p>Payment:
Credit card<input type="radio" id='radio_1' name='payment' value="credit">
<div class="text1">
<form name="cardForm" method="post">
<p>Card number:<input type="text" name="FirstField" id='card' value=""
onKeyup="autotab(this,document.cardForm.SecondField)" maxlength=16 >
Expiration: Month:-<input type="text" name="SecondField" id='Month' value=""
onKeyup="autotab(this,document.cardForm.ThirdField)" maxlength=2 >
Year:-<input type="text" id='Year' name="ThirdField" value="" onKeyup="autotab(this, document.cardForm.FourthField)"maxlength=4></p>
3 digit CVC:-<input type="text" name="FourthField" id='Cvc' value="" maxlength=3></p>
</form>
</div>
</body>
<!--Jump when expiration number is typed-->
<!--month and year-->
<!--exp date has to greater than or equal to current date -->
<!--on every keypress check if the length is 16-->
<!--macthes-->
<!-- Import numeric from src folder-->
<script src="numeric.js"></script>
<script>
//autotab doesnt work for the first feild
//can still copy and paste text
$(document).ready(function () {
$(".text1").hide();
$("#radio_1").click(function () {
<!--passes card id to keypress function-->
$('#card').keypress();
//disable copy and paste
$('#card').bind();
$('#Month').keypress();
$('#Month').bind();
$('#Month').jStepper({minValue:0, maxValue:12});
$('#Year').keypress();
$('#Year').bind();
$('#Cvc').keypress();
$('#Cvc').bind();
$(".text1").show();
});
});
</script>
<html>
/*
Auto tabbing script- By JavaScriptKit.com
http://www.javascriptkit.com
This credit MUST stay intact for use
*/
function autotab(original,destination){
if (original.getAttribute&&original.value.length==original.getAttribute("maxlength"))
destination.focus()
}
my isnumeric file
$(this).keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});
//check for the type of credit card and prints to console
$(this).keypress(function (e) {
var input = document.getElementById('card');
input.onkeyup = function() {
if(input.value.length == 16){
var str = input.value;
var VisaRegx = /^4[0-9]{6,}$/i;
var Visafound = str.match(VisaRegx);
if(Visafound != null){
console.log("Visa Found");
}
var MasterRegx = /^5[1-5][0-9]{5,}$/i;
var Masterfound = str.match(MasterRegx);
if(Masterfound != null){
console.log("Master Card Found");
}
var AmericanExpressRegx = /^3[47][0-9]{5,}$/i;
var AmericanExpressfound = str.match(AmericanExpressRegx);
if(AmericanExpressfound != null){
console.log("American Express Card Found");
}
//^(?:2131|1800|35[0-9]{3})[0-9]{3,}$
var DinersClubRegx = /^3(?:0[0-5]|[68][0-9])[0-9]{4,}$/i;
var DinersClubfound = str.match(DinersClubRegx);
if(DinersClubfound != null){
console.log("Diners Club Card Found");
}
var DiscoverRegx = /^6(?:011|5[0-9]{2})[0-9]{3,}$/i;
var Discoverfound = str.match(DiscoverRegx);
if(Discoverfound != null){
console.log("Discover Card Found");
}
var JcbRegx = /^(?:2131|1800|35[0-9]{3})[0-9]{3,}$/i;
var Jcbfound = str.match(JcbRegx);
if(Jcbfound != null){
console.log("Jcb Card Found");
}
}
}
});
//checks for credit card expiration
$(this).keypress(function (e) {
var Monthinput = document.getElementById('Month').value;
var Yearinput = document.getElementById('Year').value;
var today = new Date();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(Yearinput.length == 4){
if(yyyy > Yearinput){
console.log("The card is expired cause of the year");
}
}
if(Yearinput.length == 4 && Monthinput.length == 2){
if(yyyy == Yearinput && mm > Monthinput){
console.log("The card is expired cause of the current month");
}
}
});
//Disable copy and paste
$(this).bind("cut copy paste",function(e) {
e.preventDefault();
});

Can't retrieve RadDatePicker object from Javascript

I'm pulling my hair over this, I can't get the Client-Side API of RadDatePicker to work. The object has no function or no properties.My want is simple just want to create a object of a RadDatePicker on javascript.please check the ClearControl function.just want to use set_selectedDate method on find datepicker control object.like:
var today = new Date();
var dateAcc = $find("<%=dtpDODate.ClientID %>");
dateAcc.set_selectedDate(today);
Can you help me to find what is wrong with this code on a blank aspx page?
<script type="text/javascript" language="javascript">
function ClearControl(DivID) {
try {
var elements = null;
if (DivID == null) {
var oForm = document.forms['frmSiteMain'];
if (!oForm) {
oForm = document.form1;
}
elements = oForm.elements;
}
else {
elements = document.getElementById(DivID).getElementsByTagName("input");
}
// oForm.reset();
for (i = 0; i < elements.length; i++) {
if (elements[i].type != null) {
field_type = elements[i].type.toLowerCase();
if (field_type) {
if ((elements[i].id.toString().search("body_") == 0 || elements[i].id.toString().search("ctl00_body_") == 0) && elements[i].id.toString().indexOf("_dtp") > 0) {
var today = new Date();
var control = $find(elements[i].id.toString());
control.set_selectedDate(today);
break;
}
}
}
}
}
catch (e) {
alert(e.message + " Type:" + field_type);
}
}
</script>
<div class="p_div" id="divDODate" runat="server">
<div class="m1">
<asp:Label ID="lblDODate" runat="server" Text="Date"></asp:Label>
<telerik:RadDatePicker ID="dtpDODate" runat="server" MapColumnName="strDODate">
<DateInput ID="DateInput1" DateFormat="MM/dd/yyyy" runat="server">
</DateInput>
</telerik:RadDatePicker>
</div>
</div>
Thanks for your assistance,
The problem is specific , wrong object creation syntax,check the bellow sytax
else if ((elements[i].id.toString().search("body_") == 0 || elements[i].id.toString().search("ctl00_body_") == 0) && elements[i].id.toString().indexOf("_dtp") > 0) {
var today = new Date();//get date
var control = $find(elements[i].id.toString());//create object of date picker control
control.set_selectedDate(today);//fill picker with date.
break;
}

Enable Button during certain day & time

I am trying to enable a button ONLY during 5PM to 10PM every day, except Monday.
When the button is disabled, <p></p> should show up (like a notification to the visitor why it is disabled.)
I did try to write the JavaScript on my own, but it seem not to work correctly. I don't know anything about that language and did the script with aid of different sites.
Here is my script:
<input class="submit" type="submit" id="checktimer" value="Check"/>
<p id=timer style="display: none;">Lorem ipsum</p>
<script type="text/javascript" defer="defer">
<!--
var enableDisable = function(){
var UTC_hours = new Date().getUTCHours() +1;
var day = new Date().getDay();
if (day == 1){
document.getElementById('checktimer').disabled = true;
document.getElementById('timer').style.display = 'block';
}
else{
if (UTC_hours > 16 && UTC_hours < 22){
document.getElementById('checktimer').disabled = false;
document.getElementById('timer').style.display = 'none';
}
else
{
document.getElementById('checktimer').disabled = true;
document.getElementById('timer').style.display = 'block';
}
}
};
setInterval(enableDisable, 1000*60);
enableDisable();
// -->
</script>
This would work:
var enableDisable = function(){
var UTC_hours = new Date().getUTCHours(); //Don't add 1 here
var day = new Date().getUTCDay(); //Use UTC here also
if (day != 1 && UTC_hours >= 17 && UTC_hours < 22){
document.getElementById('checktimer').disabled = false;
document.getElementById('timer').style.display = 'none';
}else{
document.getElementById('checktimer').disabled = true;
document.getElementById('timer').style.display = 'block';
}
};
setInterval(enableDisable, 1000*60);
enableDisable();
Cheers
DEMO
Try setting the attribute on the element, instead of a property on the element object:
document.getElementById('checktimer').setAttribute('disabled');
To remove it, use
document.getElementById('checktimer').removeAttribute('disabled');
As others have mentioned, you should cache the checktimer element in a variable, instead of looking it up each time.
A couple of other minor things I changed:
Removed those Javascript comment things you had. You don't need those.
Added quotes around the value of the id attribute for your p element.
Actually, you shouldn't enable or disable the button based on JavaScript DateTime because it gets the client machine's date, meaning that if the user changes it's system date the button will be enabled. You should verify it on the server-side code, such as PHP or ASP. There, you can check for datetime validation, and write the button on the page, or not.
Just get rid of the HTML comment <!-- or comment it with //
<script type="text/javascript">
//<!--
var enableDisable = function(){
var UTC_hours = new Date().getUTCHours() +1;
var day = new Date().getDay();
if (day == 1){
document.getElementById('checktimer').disabled = true;
document.getElementById('timer').style.display = 'block';
}
else{
if (UTC_hours > 16 && UTC_hours < 22){
document.getElementById('checktimer').disabled = false;
document.getElementById('timer').style.display = 'none';
}
else
{
document.getElementById('checktimer').disabled = true;
document.getElementById('timer').style.display = 'block';
}
}
};
setInterval(enableDisable, 1000*60);
enableDisable();
// -->
</script>
Your script should then work normally

How to check for links in textbox JavaScript [duplicate]

This question already has answers here:
How to look for a word in textbox in JavaScript
(3 answers)
Closed 8 years ago.
If there is a link in a textbox then JavaScript will redirect the user to the link when they press a button. For example if the textbox has www.google.com in it the JavaScript would see the "www." and it would play a function which redirects the user to the link entered. Here is my code:
JavaScript:
function showAlert() {
var txtCtrl = document.getElementById("textbox1");
var txtVal = txtCtrl.value;
var txtValUpper = txtVal.toUpperCase();
var txtValLower = txtVal.toLowerCase();
if (txtVal == '') {
alert('Please fill in the text box. For a list of commands type "Help" into the text box.');
} else if (txtValUpper == 'start' || txtValLower == 'start') {
alert('Hello. What would you like me to do?');
} else if (txtValUpper.indexOf("weather") != -1 || txtValLower.indexOf("weather") != -1) {
window.location = "https://www.google.com/#q=weather";
} else if (txtValUpper.indexOf("time") != -1 || txtValLower.indexOf("time") != -1) {
alert('The current time according to your computer is' + formatTime(new Date()));
} else if (txtValUpper.indexOf("help") != -1 || txtValLower.indexOf("help") != -1) {
window.location = "help/index.html";
} else if (txtValUpper.indexOf("donate") != -1 || txtValLower.indexOf("donate") != -1) {
window.location = "donate/index.html";
} else {
alert('Sorry, I do not reconise that command. For a list of commands, type "Help" into the text box.');
}
}
//Show time in 24hour format
function showTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
return [h, m].join(':')
}
//Show time in 12hour format
var formatTime = (function () {
function addZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
return function (dt) {
var formatted = '';
if (dt) {
var hours24 = dt.getHours();
var hours = ((hours24 + 11) % 12) + 1;
formatted = [formatted, [addZero(hours), addZero(dt.getMinutes())].join(":"), hours24 > 11 ? "PM" : "AM"].join(" ");
}
return formatted;
}
})();
And HTML:
<!doctype html>
<html>
<head>
<title>Random Project</title>
</head>
<body>
<div class="container">
<img class="logo" src="logo.png" width="450" height="110" alt="Random Project">
<input type="text" name="textbox1" value="" spellcheck="false" dir="ltr" placeholder="Type here" id="textbox1"><br>
<button id="button1" name="button1" aria-label="Help me" onClick="showAlert();">
<span id="button1_text">Help me</span>
</button>
<div class="separator"></div>
<span class="information">© Copyright DemDevs 2013. All rights reserved. Made by Omar Latreche<br>Donate now</span>
<div class="tip">
<span class="tip">Tip: </span><span class="tip_text">The commands are NOT case sensitive</span>
</div>
<div class="example">
<span class="example">Example: </span><span class="tip_text">Show me the weather or What is the current time</span>
</div>
</div>
<div class=""></div>
</body>
</html>
Any help will be greatly appreciated.
Thanks, Omar!
Use pattern matching for this:
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
var t = 'www.google.com'; // you would change this to dynamically check text input
if(t.match(regex))
{
// Execute your code
}

How can I make my elements fade in and out as their display attributes are changed in Javascript?

On the click of a button (using onclick), I am toggling the display style of three divs between none and block. I am at a loss as to how I can make these divs fade in and out. I am open to using JQuery as well but I do not see how I could integrate andéor use the fadeIn() and fadeOut() functions here. Any suggestions as to how I can go about doing this would be greatly appreciated.
Below is the function that is being called onclick for reference, this is where the display attribute of my divs is toggled.
function divSelector(count){
if (count == 1){
var temp = document.getElementById('second-about-text');
temp.style.display = 'none';
temp = document.getElementById('third-about-text');
temp.style.display = 'none';
temp = document.getElementById('first-about-text');
temp.style.display = 'block';
}
else if (count == 2){
var temp = document.getElementById('first-about-text');
temp.style.display = 'none';
temp = document.getElementById('third-about-text');
temp.style.display = 'none';
temp = document.getElementById('second-about-text');
temp.style.display = 'block';
}
else if (count == 3){
var temp = document.getElementById('first-about-text');
temp.style.display = 'none';
temp = document.getElementById('second-about-text');
temp.style.display = 'none';
temp = document.getElementById('third-about-text');
temp.style.display = 'block';
}
else{
console.log("Count is nothing.");
}
}
Since you are open to JQuery try this way:
I am just assuming your markup here. Give a common class to your divs say content so that they are accessible with one selector.
$('.content:gt(0)').hide(); //start up hide all but the first one.
function divSelector(count){
var currElem = $('.content:eq(' + count-1 + ')'); //get the div based on the count number eq will give the div based on its index and position in DOM. Assuming these divs appear in DOM one after the other.
$('.content').not(currElem).fadeOut('1000', function(){ //Fade out other content divs
currElem.fadeIn('1000'); //Fade in the current one.
});
}
:gt()
:eq()
:fadeIn()
:fadeOut()
providing your markup will clear out the assumptions and help provide a better solution.
Here is a fully contained example for you:
jsFiddle here
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style>
.btn {height:50px;width:50px;margin:50px 50px;}
.one{background-color:red;}
.two{background-color:green;}
.three{background-color:blue;}
</style>
<script type="text/javascript">
$(document).ready(function() {
count = 1;
$('#mybutt').click(function() {
divSelector(count);
count++;
if (count==4) count = 1;
});
function divSelector(count){
if (count == 1){
$('#first-about-text').fadeIn(1000);
$('#second-about-text').hide();
$('#third-about-text').fadeOut(1000);;
}else if (count == 2){
$('#first-about-text').fadeOut(1000);
$('#second-about-text').fadeIn(1000);
$('#third-about-text').hide();;
}else if (count == 3){
$('#first-about-text').hide();
$('#second-about-text').fadeOut(1000);
$('#third-about-text').fadeIn(1000);;
}else{
console.log("Count is nothing.");
}
}
}); //END $(document).ready()
</script>
</head>
<body>
<div id="first-about-text" class="btn one"></div>
<div id="second-about-text" class="btn two"></div>
<div id="third-about-text" class="btn three"></div>
<input type="button" id="mybutt" value="Click Me">
</body>
</html>
Is it what you need?
function divSelector(count){
if (count == 1){
$('#second-about-text').fadeOut();
$('#third-about-text').fadeOut();
$('#first-about-text').fadeIn();
}
else if (count == 2){
$('#second-about-text').fadeIn();
$('#third-about-text').fadeOut();
$('#first-about-text').fadeOut();
}
else if (count == 3){
$('#second-about-text').fadeOut();
$('#third-about-text').fadeIn();
$('#first-about-text').fadeOut();
}
else{
console.log("Count is nothing.");
}
}

Categories

Resources