Javascript Showing div function - javascript

<script language="javascript">
function switchdiv() {
var e = document.getElementById().id;
if(e == 'Streambtn')
document.getElementById('Stream').style.display = "block";
else
document.getElementById('Stream').style.display = "none";
}
</script>
Hello,
Here is my problem. When I click, nothing happen...
I hope you can help me.
Thank you
Edit :
Thank you for your answer zzlalani but it unfortunately does not work.
Here is the final code, hoping you'll help me to find a way to fix the problem.
<div align="center">
<input type="button" class="btn" name="Stream" value="Stream" style="padding: 10px 20px 10px 20px; border: 0px; font-family: Play, sans-serif; font-weight: bold" onClick="switchdiv("Streambtn")"/>
<input type="button" class="btn" name="Youtube" value="Youtube" style="padding: 10px 20px 10px 20px; border: 0px; font-family: Play, sans-serif; font-weight: bold" onClick="switchdiv("Youtubebtn")"/>
<input type="button" class="btn" name="LoL" value="League Of Legends" style="padding: 10px 20px 10px 20px; border: 0px; font-family: Play, sans-serif; font-weight: bold" onClick="switchdiv("LoLbtn")"/>
</div>
<script language="javascript">
function switchdiv(e) {
if(e == 'Streambtn')
document.getElementById('Stream').style.display = "block";
else
document.getElementById('Stream').style.display = "none";
}
if(e == 'Youtubebtn')
document.getElementById('Youtube').style.display = "block";
else
document.getElementById('Youtube').style.display = "none";
}
if(e == 'LoLbtn')
document.getElementById('LoL').style.display = "block";
else
document.getElementById('LoL').style.display = "none";
}
</script>
<div align="center" id="Stream" hidden>
<p>a</p>
</div>
<div align="center" id="Youtube" hidden>
<p>b</p>
</div>
<div align="center" id="LoL" hidden>
<p>c</p>
</div>

Let say you have button that calls switchdiv on click
<input type='button' onClick='switchdiv("Streambtn");' value='Stream!'>
<input type='button' onClick='switchdiv("nonStreambtn");' value='Non Stream!'>
Then it will goes like this
<script language="javascript">
function switchdiv(e) {
if(e == 'Streambtn')
document.getElementById('Stream').style.display = "block";
else
document.getElementById('Stream').style.display = "none";
}
</script>
The problem in you code is you are getting the value of nothing.. check it in this way
var e = document.getElementById().id;
console.log(e);
in the console of the browser you can see that will be either show some weird errors in red

Related

Show child elements if parent is visible

I'm trying to have my form show child elements if the parent is visible and I keep getting an "undefined" error with my child element, even though I have it defined. I'm trying to have set this up where:
Q1: Checked responses will show parent elements (divs).
Q2: Depending on this response, it'll show child elements (divs).
Is there a way to do this?
//Next Tab
function next() {
var formTabOne = document.getElementById("stepOne");
formTabOne.classList.add("formTrans");
formTabOne.addEventListener("transitionend", function({
target
}) {
if (target === formTabOne) {
target.classList.add("hidden");
target.classList.remove("formTrans");
document.getElementById("stepTwo").classList.remove("hidden");
}
})
}
//Prev Tab
function prev() {
var formTabTwo = document.getElementById("stepTwo");
formTabTwo.classList.add("formTrans");
formTabTwo.addEventListener("transitionend", function({
target
}) {
if (target === formTabTwo) {
target.classList.add("hidden");
target.classList.remove("formTrans");
document.getElementById("stepOne").classList.remove("hidden");
}
})
}
function process() {
var form = document.myForm;
var biz = document.getElementById("biz");
var career = document.getElementById("career");
var change = document.getElementById("change");
var eq = document.getElementById("eq");
var empathy = document.getElementById("empathy");
var pm = document.getElementById("pm");
var bizMgr = document.getElementsByClassName("bizMgr");
var bizEE = document.getElementsByClassName("bizEE");
//Q1 - Topics
document.querySelectorAll("#chkTopic input").forEach((el) => {
const contentID = el.id.replace("chk", "").toLowerCase()
document.getElementById(contentID).style.display = el.checked ? "block" : "none";
});
//Q2 - Employee Type
var q2value = "";
for (var i = 0; i < form.q2.length; i++) {
var answer = form.q2[i];
if (answer.checked) {
q2value = answer.value;
}
}
if (q2value == "1") {
if (biz.style.display = "block") {
bizMgr.style.display = "block";
bizEE.style.display = "block";
}
} else {
if (biz.style.display = "block") {
document.getElementsByClassName("bizEE").style.display = "block";
}
}
}
html {
scroll-behavior: smooth;
}
#formWrapper {
background-color: #eaeaea;
padding: 20px;
margin-bottom: 40px;
min-height: 300px;
}
#myForm {
width: 70%;
min-height: 280px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
border: 1px solid #dedede;
box-sizing: border-box;
}
.formStep {
opacity: 1;
background: #fff;
}
.formTrans {
visibility: hidden;
opacity: 0;
transition: visibility 0s 200ms, opacity 200ms linear;
}
.hidden {
display: none;
}
#biz, #career, #change, #eq, #empathy, #pm, #pd {
display: none;
width: 100%;
min-height: 200px;
box-sizing: border-box;
margin-bottom: 30px;
border: 1px solid #000;
}
.bizMgr, .bizEE, .careerMgr, .careerEE, .changeMgr, .changeEE, .eqMgr, .eqEE, .empathyMgr, .empathyEE, .pmMgr, .pmEE, .pdMgr, .pdEE {
display: none;
}
<form name="myForm" id="myForm">
<input type="button" value="Skip This" onclick="formSkip();">
<br><br>
<!--Step 1-->
<div id="stepOne" class="formStep">
<b>Select the topic(s) you're interested in:</b><br>
<div id="chkTopic">
<input id="chkBiz" type="checkbox" value="1"><label for="chkBiz">Business Structure/Acumen</label><br>
<input id="chkCareer" type="checkbox" value="2"><label for="chkCareer">Career Development</label><br>
<input id="chkChange" type="checkbox" value="3"><label for="chkChange">Change</label><br>
<input id="chkEQ" type="checkbox" value="4"><label for="chkEQ">Emotional Intelligence</label><br>
<input id="chkEmpathy" type="checkbox" value="5"><label for="chkEmpathy">Empathy</label><br>
<input id="chkPM" type="checkbox" value="6"><label for="chkPM">Performance Management</label><br>
</div>
<br>
<button type="button" id="btnStepOne" onclick="next();">Next</button>
</div>
<!--Step 2-->
<div id="stepTwo" class="formStep hidden">
<b>Are you a people leader?</b><br>
<input type="radio" name="q2" value="0">No<br>
<input type="radio" name="q2" value="1">Yes<br>
<br>
<button type="button" id="btnStepTwo" onclick="prev();">Previous</button>
<input type="button" value="Show Results" onclick="process();">
<input type="reset" value="Start Over" onclick="formReset();">
</div>
</form>
<div id="results">
<div id="biz">
Business Structure/Acumen
<div class="bizMgr">Manager Content</div>
<div class="bizEE">Employee Content</div>
</div>
<div id="career">
Career Development
<div class="careerMgr">Manager Content</div>
<div class="careerEE">Employee Content</div>
</div>
<div id="change">
Change
<div class="changeMgr">Manager Content</div>
<div class="changeEE">Employee Content</div>
</div>
<div id="eq">
Emotional Intelligence
<div class="eqMgr">Manager Content</div>
<div class="eqEE">Employee Content</div>
</div>
<div id="empathy">
Empathy
<div class="empathyMgr">Manager Content</div>
<div class="empathyEE">Employee Content</div>
</div>
<div id="pm">
Performance Management
<div class="pmMgr">Manager Content</div>
<div class="pmEE">Employee Content</div>
</div>
</div>
.getElementsByClassName returns a collection, bizMgr and bizEE are both collections. You have to iterate the collections and set each element to style.display = 'block'. You can't just call xxx.style.display on a javascript collection. You would want to change your code like the following:
if (q2value == "1") {
if (biz.style.display = "block") {
//bizMgr.style.display = "block"; -NO
//bizEE.style.display = "block"; -NO
for(let i = 0; i < bizMgr.length; i++){
bizMgr[i].style.display = "block";
}
for(let j = 0; j < bizEE.length; j++){
bizEE[j].style.display = "block";
}
}
} else {
if (biz.style.display = "block") {
//document.getElementsByClassName("bizEE").style.display = "block"; -NO
for(let j = 0; j < bizEE.length; j++){
bizEE[j].style.display = "block";
}
}
}

Why does my page refresh when I press buttons?

This is the relevant code of my page :
HTML :
<button class="ajout-col"><i class="fas fa-columns"> Ajouter une colonne</i></button>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th></th>
<th>
<button class="btn"><i class="fas fa-trash remove-col"></i></button>
<button class="btn"><i class="fas fa-text-height text-col"></i></button>
<button class="btn"><i class="fas fa-sort-numeric-down nbr-col"></i></button>
<input type="text" class="form-control">
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<button class="btn"><i class="fas fa-trash remove-row"></i></button>
</td>
<td>
<input type="text" class="form-control">
</td>
</tr>
</tbody>
</table>
</div>
<button class="ajout-lig"><i class="fas fa-list-ul"> Ajouter une ligne</i></button>
Javascript :
$('body').on('click', '.remove-row', function() {
$(this).parents('tr').remove();
});
(Any button of the grid refreshes my page, I just put the remove-row one because it's the shortest code only for clarity purpose)
(Issue is located on the second tab, just fill info on the first tab to be able to access the second tab)
Any time I press a button from the grid, it refreshes my page
I searched on google and it appears I have to add "return false" or "e.preventDefault();" to fix the issue, and I tried, but it only fixes partially the issue
If I add any of those at the end of each .on('click'), it fixes the issue for Adding a column or a row
But deleting a row or a column is going to work 1 or 2 times, and then my page is going to refresh again... same for the other buttons (text and number buttons)
Thanks in advance for any help ! :)
// Code goes here
$(document).ready(function() {
// add row
$('body').on('click', '.ajout-lig', function() {
var tr = $(this).parents('.table-content').find('.table tbody tr:last');
if (tr.length > 0) {
var clone = tr.clone();
clone.find(':text').val('');
tr.after(clone);
} else {
var cols = $(this).closest('.table-content').find('th').length,
tr0 = $('<tr/>');
tr0.html('<td><button class="btn"><i class="fa fa-trash remove-row"></i></button></td><td> <input type="text" class="form-control"> </td>');
for (var i = 2; i < cols; i++) {
tr0.append('<td> static element </td>')
}
$(this).closest('.table-content').find('.table tbody').append(tr0);
}
});
// delete row
$('body').on('click', '.remove-row', function() {
$(this).parents('tr').remove();
});
// add column
$('body').on('click', '.ajout-col', function() {
$(this).parent().find('.table thead tr').append('<th><button class="btn"><i class="fas fa-trash remove-col"></i></button> <button class="btn"><i class="fas fa-text-height text-col"></i></button> <button class="btn"><i class="fas fa-sort-numeric-down nbr-col"></i></button> <input type="text" class="form-control pull-left" value=""></th>');
$(this).parent().find('.table tbody tr').append('<td><input type="text" class="form-control"></td>');
});
// change column type to text
$('body').on('click', '.text-col', function(event) {
let ndx = $(this).parent().index() + 1;
let inputsCol = $('.table tbody tr td:nth-child(' + ndx + ') input');
inputsCol.attr("type", "text");
});
// change column type to number
$('body').on('click', '.nbr-col', function(event) {
var filter = /^[0-9]*$/g;
var cond = false;
var min = prompt('Valeur minimum :');
while (cond == false) {
if (min.match(filter)) {
cond = true;
} else {
var min = prompt('Valeur minimum incorrect, réessayez :');
}
}
var cond = false;
var max = prompt('Valeur maximum :');
while (cond == false) {
if (max.match(filter)) {
cond = true;
} else {
var max = prompt('Valeur maximum incorrect, réessayez :');
}
}
let ndx = $(this).parent().index() + 1;
let inputsCol = $('.table tbody tr td:nth-child(' + ndx + ') input');
inputsCol.attr("type", "number").prop("min", min).prop("max", max);
//console.log("inputs modified, example:", inputsCol2[0])
});
// remove column
$('body').on('click', '.remove-col', function(event) {
// Get index of parent TD among its siblings (add one for nth-child)
var ndx = $(this).parent().index() + 1;
// Find all TD elements with the same index
$('th', event.delegateTarget).remove(':nth-child(' + ndx + ')');
$('td', event.delegateTarget).remove(':nth-child(' + ndx + ')');
});
});
$(document).ready(function(){
$('#btn_login_details').click(function(){
var error_date = '';
var error_titre = '';
var error_entreprise = '';
var error_conseiller = '';
var filter = /^([0-2][0-9]|(3)[0-1])(\/)(((0)[0-9])|((1)[0-2]))(\/)\d{4}$/;
if($.trim($('#titre').val()).length == 0)
{
error_titre = 'Titre requis !';
$('#error_titre').text(error_titre);
$('#titre').addClass('has-error');
}
else
{
error_titre = '';
$('#error_titre').text(error_titre);
$('#titre').removeClass('has-error');
}
if($.trim($('#entreprise').val()).length == 0)
{
error_entreprise = 'Nom de l\'entreprise requis !';
$('#error_entreprise').text(error_entreprise);
$('#entreprise').addClass('has-error');
}
else
{
error_entreprise = '';
$('#error_entreprise').text(error_entreprise);
$('#entreprise').removeClass('has-error');
}
if($.trim($('#conseiller').val()).length == 0)
{
error_conseiller = 'Nom du conseiller requis !';
$('#error_conseiller').text(error_conseiller);
$('#conseiller').addClass('has-error');
}
else
{
error_conseiller = '';
$('#error_conseiller').text(error_conseiller);
$('#conseiller').removeClass('has-error');
}
if($.trim($('#date').val()).length == 0)
{
error_date = 'Date requise !';
$('#error_date').text(error_date);
$('#date').addClass('has-error');
}
else
{
if (!filter.test($('#date').val()))
{
error_date = 'Date invalide';
$('#error_date').text(error_date);
$('#date').addClass('has-error');
}
else
{
error_date = '';
$('#error_date').text(error_date);
$('#date').removeClass('has-error');
}
}
if((error_titre != '') || (error_conseiller != '') || (error_entreprise != '') || (error_date != ''))
{
return false;
}
else
{
$('#list_login_details').removeClass('active active_tab1');
$('#list_login_details').removeAttr('href data-toggle');
$('#login_details').removeClass('active');
$('#list_login_details').addClass('inactive_tab1');
$('#list_personal_details').removeClass('inactive_tab1');
$('#list_personal_details').addClass('active_tab1 active');
$('#list_personal_details').attr('href', '#personal_details');
$('#list_personal_details').attr('data-toggle', 'tab');
$('#personal_details').addClass('active in');
}
});
$('#previous_btn_personal_details').click(function(){
$('#list_personal_details').removeClass('active active_tab1');
$('#list_personal_details').removeAttr('href data-toggle');
$('#personal_details').removeClass('active in');
$('#list_personal_details').addClass('inactive_tab1');
$('#list_login_details').removeClass('inactive_tab1');
$('#list_login_details').addClass('active_tab1 active');
$('#list_login_details').attr('href', '#login_details');
$('#list_login_details').attr('data-toggle', 'tab');
$('#login_details').addClass('active in');
});
$('#btn_gen_grille').click(function() {
// Générer la grille
// Ici
});
$('#btn_personal_details').click(function(){
$('#list_personal_details').removeClass('active active_tab1');
$('#list_personal_details').removeAttr('href data-toggle');
$('#personal_details').removeClass('active');
$('#list_personal_details').addClass('inactive_tab1');
$('#list_contact_details').removeClass('inactive_tab1');
$('#list_contact_details').addClass('active_tab1 active');
$('#list_contact_details').attr('href', '#contact_details');
$('#list_contact_details').attr('data-toggle', 'tab');
$('#contact_details').addClass('active in');
});
$('#previous_btn_contact_details').click(function(){
$('#list_contact_details').removeClass('active active_tab1');
$('#list_contact_details').removeAttr('href data-toggle');
$('#contact_details').removeClass('active in');
$('#list_contact_details').addClass('inactive_tab1');
$('#list_personal_details').removeClass('inactive_tab1');
$('#list_personal_details').addClass('active_tab1 active');
$('#list_personal_details').attr('href', '#personal_details');
$('#list_personal_details').attr('data-toggle', 'tab');
$('#personal_details').addClass('active in');
});
$('#btn_contact_details').click(function(){
var error_address = '';
var error_mobile_no = '';
var mobile_validation = /^\d{10}$/;
if($.trim($('#address').val()).length == 0)
{
error_address = 'Address is required';
$('#error_address').text(error_address);
$('#address').addClass('has-error');
}
else
{
error_address = '';
$('#error_address').text(error_address);
$('#address').removeClass('has-error');
}
if($.trim($('#mobile_no').val()).length == 0)
{
error_mobile_no = 'Mobile Number is required';
$('#error_mobile_no').text(error_mobile_no);
$('#mobile_no').addClass('has-error');
}
else
{
if (!mobile_validation.test($('#mobile_no').val()))
{
error_mobile_no = 'Invalid Mobile Number';
$('#error_mobile_no').text(error_mobile_no);
$('#mobile_no').addClass('has-error');
}
else
{
error_mobile_no = '';
$('#error_mobile_no').text(error_mobile_no);
$('#mobile_no').removeClass('has-error');
}
}
if(error_address != '' || error_mobile_no != '')
{
return false;
}
else
{
$('#btn_contact_details').attr("disabled", "disabled");
$(document).css('cursor', 'prgress');
$("#register_form").submit();
}
});
});
/* Style the header with a grey background and some padding */
* {box-sizing: border-box;}
body {
margin: 0;
font-family: Arial, Helvetica, sans-serif;
}
.header {
overflow: hidden;
background-color: #f1f1f1;
padding: 20px 10px;
}
.header a {
float: left;
color: black;
text-align: center;
padding: 12px;
text-decoration: none;
font-size: 18px;
line-height: 25px;
border-radius: 4px;
}
.header a.logo {
font-size: 25px;
font-weight: bold;
}
.header a:hover {
background-color: #ddd;
color: black;
}
.header a.active {
background-color: dodgerblue;
color: white;
}
.header-right {
float: right;
}
#media screen and (max-width: 500px) {
.header a {
float: none;
display: block;
text-align: left;
}
.header-right {
float: none;
}
}
.contenuaccueil {
text-align: center;
position : absolute;
width : 100%;
color : black;
top:50%;
left:50%;
transform:translate(-50%,-50%);
}
.background
{
margin-top : 10%;
margin-bottom : 10%;
position:relative;
text-align: center;
}
.img
{
background-repeat: repeat-x;
width: 100%;
height: auto;
text-align: center;
}
footer {
text-align : center;
padding-top: 10px;
padding-bottom: 0px;
bottom:0;
width:100%;
color : #A5A5A5;
font-family : "Lato", sans-serif;
font-size : 15px;
font-weight : 400;
text-transform : uppercase;
text-decoration : none;
letter-spacing : 3px;
}
.box
{
width:800px;
margin:0 auto;
}
.active_tab1
{
background-color:#fff;
color:#333;
font-weight: 600;
}
.inactive_tab1
{
background-color: #f5f5f5;
color: #333;
cursor: not-allowed;
}
.has-error
{
border-color:#cc0000;
background-color:#ffff99;
}
/* Styles go here */
.table-content {
padding: 20px;
}
.form-control {
width: 90px;
}
/* Style buttons */
.ajout-lig,.ajout-col {
background-color: DodgerBlue; /* Blue background */
border: none; /* Remove borders */
color: white; /* White text */
padding: 12px 16px; /* Some padding */
font-size: 16px; /* Set a font size */
cursor: pointer; /* Mouse pointer on hover */
border-radius: 5px;
}
/* Darker background on mouse-over */
.ajout-lig:hover,.ajout-col:hover {
background-color: RoyalBlue;
}
<html>
<head>
<title>Innovatech</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="css/custom.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://kit.fontawesome.com/38b99a3f0e.js" crossorigin="anonymous"></script>
</head>
<body>
<!-- Titre + Menu -->
<div class="header">
Innovatech
<div class="header-right">
Accueil
<a class="active" href="ajout.php">Nouveau</a>
Modifier
Mode d'emploi
</div>
</div>
<!-- Contenu du site web -->
<div class="contenu">
<br />
<div class="container box">
<br />
<h2 align="center">Ajout d'un nouvel audit</h2><br />
<?php echo $message; ?>
<form method="post" id="register_form">
<ul class="nav nav-tabs">
<li class="nav-item">
<a class="nav-link active_tab1" style="border:1px solid #ccc" id="list_login_details">Informations à propos de l'entreprise</a>
</li>
<li class="nav-item">
<a class="nav-link inactive_tab1" id="list_personal_details" style="border:1px solid #ccc">Grille d'audit</a>
</li>
<li class="nav-item">
<a class="nav-link inactive_tab1" id="list_contact_details" style="border:1px solid #ccc">Génération des graphiques</a>
</li>
</ul>
<div class="tab-content" style="margin-top:16px;">
<div class="tab-pane active" id="login_details">
<div class="panel panel-default">
<div class="panel-heading">Informations à propos de l'entreprise</div>
<div class="panel-body">
<div class="form-group">
<label>Titre de l'audit</label>
<input type="text" name="titre" id="titre" class="form-control" />
<span id="error_titre" class="text-danger"></span>
</div>
<div class="form-group">
<label>Nom de l'entreprise</label>
<input type="text" name="entreprise" id="entreprise" class="form-control" />
<span id="error_entreprise" class="text-danger"></span>
</div>
<div class="form-group">
<label>Nom du conseiller</label>
<input type="text" name="conseiller" id="conseiller" class="form-control" />
<span id="error_conseiller" class="text-danger"></span>
</div>
<div class="form-group">
<label>Date de l'interview (jj/mm/aaaa)</label>
<input type="text" name="date" id="date" class="form-control" />
<span id="error_date" class="text-danger"></span>
</div>
<br />
<div align="center">
<button type="button" name="btn_login_details" id="btn_login_details" class="btn btn-info btn-lg">Suivant</button>
</div>
<br />
</div>
</div>
</div>
<div class="tab-pane fade" id="personal_details">
<div class="panel panel-default">
<div class="panel-heading">Grille d'audit</div>
<div class="panel-body">
<div class="table-content">
<button class="ajout-col"><i class="fas fa-columns"> Ajouter une colonne</i></button>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th></th>
<th>
<button class="btn"><i class="fas fa-trash remove-col"></i></button>
<button class="btn"><i class="fas fa-text-height text-col"></i></button>
<button class="btn"><i class="fas fa-sort-numeric-down nbr-col"></i></button>
<input type="text" class="form-control">
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<button class="btn"><i class="fas fa-trash remove-row"></i></button>
</td>
<td>
<input type="text" class="form-control">
</td>
</tr>
</tbody>
</table>
</div>
<button class="ajout-lig"><i class="fas fa-list-ul"> Ajouter une ligne</i></button>
</div>
<br />
<div align="center">
<button type="button" name="previous_btn_personal_details" id="previous_btn_personal_details" class="btn btn-default btn-lg">Précédent</button>
<button type="button" name="btn_personal_details" id="btn_personal_details" class="btn btn-info btn-lg">Suivant</button>
</div>
<br />
</div>
</div>
</div>
<!--A MODIFIER - PARTIE SUR LES GRAPHIQUES-->
<div class="tab-pane fade" id="contact_details">
<div class="panel panel-default">
<div class="panel-heading">Fill Contact Details</div>
<div class="panel-body">
<div class="form-group">
<label>Enter Address</label>
<textarea name="address" id="address" class="form-control"></textarea>
<span id="error_address" class="text-danger"></span>
</div>
<div class="form-group">
<label>Enter Mobile No.</label>
<input type="text" name="mobile_no" id="mobile_no" class="form-control" />
<span id="error_mobile_no" class="text-danger"></span>
</div>
<br />
<div align="center">
<button type="button" name="previous_btn_contact_details" id="previous_btn_contact_details" class="btn btn-default btn-lg">Précédent</button>
<button type="button" name="btn_contact_details" id="btn_contact_details" class="btn btn-success btn-lg">Enregistrer</button>
</div>
<br />
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<!-- Le pied de page -->
<footer>
<p>
Innovatech <?php echo date("Y");?> - All rights reserved
</p>
</footer>
<script src="jss/ajout.js"></script>
<script src="jss/gengrille.js"></script>
</body>
</html>
This happens because a button with no type attribute acts as type="submit" and also try to submit the form data to server and refresh the page finally. Please try to set the type to the buttons like type="button" for no page refreshes.
<button class="ajout-col" type="button">
<i class="fas fa-columns"> Ajouter une colonne</i>
</button>
Replace <button class="ajout-lig"><i class="fas fa-list-ul"> Ajouter une ligne</i></button>
to
<button class="ajout-lig" type="button"><i class="fas fa-list-ul"> Ajouter une ligne</i></button>
I think this problem is due to, these buttons are actually submitting the form. if we doesn't specify the button type, it will take as a submit type button

Validation for email or phone number for same text field in angularjs

I am working on registration form for my project in AngularJs. Users can register with his/her Email/Phone. I need to validate that particular text-box.
I have validations for both, with different text fields, with ng-pattern. But how can I validate for both in one text field?
I have updated my code, here:- enter code here
http://plnkr.co/edit/mCVxHxl2DIvqOYtVapRN?p=preview
Use /^([_a-z0-9]+(\.[_a-z0-9]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,5}))|(\d+$)$/
Demo
You can use a pipe '|' to OR two regular expressions together:
/<email-pattern>|<phone-pattern>/
so your final regex would be:
/^([_a-z0-9]+(\.[_a-z0-9]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,5}))|\d+$/
You can use angular form validation and ng-pattern directive for input use ng-pattern="/^(?:\d{10}|\w+#\w+\.\w{2,3})$/"
Working Demo
var app = angular.module("MY_APP", []);
app.controller("MyCtrl", function($scope) {
$scope.submitted = false;
$scope.submit = function(userData){
console.log(userData)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MY_APP">
<div ng-controller="MyCtrl">
<form name="userForm" novalidate ng-submit="userForm.$valid && submit(userData)">
<div class="errorMsg" ng-show="submitted==true && userForm.$invalid">
<ul>
<li ng-show="submitted==true && userForm.emailphone.$error" class="errorMsg">
wrong format, It should be email or 10 digit mobile number
</li>
</ul>
</div>
<input type="text" name="emailphone" ng-model="userData.user" id="emailphone" required
ng-pattern="/^(?:\d{10}|\w+#\w+\.\w{2,3})$/" />
<button type="submit" ng-click="submitted = true">Submit</button>
</form>
</div>
</div>
guys here is the Regex for email or phone number Please have look I hope it's helpful.
Thanks
^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})|(^[0-9]{10})+$
Here is an example as well.
https://jsfiddle.net/sanat/b2m436L5/17/
function validate(){
var value = $("#email_phone").val();
var regex = new RegExp('^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})|(^[0-9]{10})+$');
if(value){
if(!regex.test(value)){
$("#error").text("Please enter valid email address or phone number.")
}else{
$("#error").text('')
}
}else{
$("#error").text('This field is required.')
}
}
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#banner-message.alt button {
background: #fff;
color: #000;
}
#error{
font-size:14px;
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
<div>
<input type="text" placeholder="Email/phone" id="email_phone">
<button onClick="validate()">Submit</button>
</div>
<span id="error"></span>
</div>
This code might work for you: Here is the ans of your question
<script type="text/javascript">
function validate(){
var phoneNo = document.getElementById('txtEmailormob');
var c=document.forms["myForm"]["email"].value;
var atpos=c.indexOf("#");
var dotpos=c.lastIndexOf(".");
var errorMsg = document.getElementById("errorMsg");
var successMsg = document.getElementById("successMsg");
if(phoneNo.value==""||phoneNo.value==null){
errorMsg.style.display="block";
document.getElementById("errorMsg").innerHTML = "Please enter your Mobile No or Email ";
return false;
}
if ((phoneNo.value.length < 10 || phoneNo.value.length > 10) && (atpos<1 || dotpos<atpos+2 || dotpos+2>=c.length)) {
errorMsg.style.display = "block";
successMsg.style.display = "none";
document.getElementById("errorMsg").innerHTML = " Mobile No. is not valid, Please Enter 10 Digit Mobile No or Please Enter valid Email. ";
return false;
}
successMsg.style.display = "block";
document.getElementById("successMsg").innerHTML = " Success ";
errorMsg.style.display = "none";
return true;
}
</script>
Simple code
Complete Working Like Validate : amazon, Facebook, uber.etc Email or Phone Number Using Single Input...
Try this its working ..............
<script>
$(document).ready(function () {
$("#cuntryCode").hide();
$("#useridInput").on('input', function () {
var len = $("#useridInput").val().length;
if (len >= 2) {
var VAL = this.value;
var intRegex = /^[1-9][0-9]*([.][0-9]{2}|)$/;
if (!intRegex.test(VAL)) {
$('#error-caption').html('Invalid email. Please check spelling.');
$('#error-caption').css('color', 'red');
$("#cuntryCode").hide();
} else {
if(len < 10){
$('#error-caption').html('Invalid mobile number. Please try again.');
$('#error-caption').css('color', 'red');
$("#cuntryCode").show();
}else{
$('#error-caption').html('Invalid mobile number. length must be 10 digit.');
$('#error-caption').css('color', 'red');
}
}
}else{
$("#cuntryCode").hide();
$('#error-caption').html('');
}
});
});
</script>
<form class="push--top-small forward" method="POST" data-reactid="15">
<h4 id="input-title" data-reactid="16">Welcome back
</h4>
<label class="label" id="input-label" for="useridInput" data-reactid="17">Sign in with your email address or mobile number.
</label>
<div style="margin-bottom:24px;" data-reactid="18">
<div >
<div id="cuntryCode" class="_style_4kEO6r" style="float: left; height: 44px; line-height: 44px;">
<div tabindex="0" > +241
</div>
</div>
<div style="display:flex;">
<input id="useridInput" autocorrect="off" autocapitalize="off" name="textInputValue" class="text-input" placeholder="Email or mobile number" aria-required="true" aria-invalid="false" aria-describedby="error-caption input-title">
</div>
</div>
<div id="error-caption">
</div>
</div>
<button class="btn btn--arrow btn--full" data-reactid="24">
<span class="push-small--right" data-reactid="25">Next
</span>
</button>
</form>

Javascript div show hide onclick with image sprite

I am trying to work on writing a div swap with images using javascript. I have created two divs. One which is display block, and the second div which is display none. When the user clicks on the image, an onclick is supposed to hide the showing div and show the hidden div in it's place.
When the user clicks the same image location, the image shifts based on the xy value and the divs are supposed to swap out again. I cannot seem to get this to function correctly. I can get the click to swap out the divs when I don't set the display on either divs, but that leaves both divs showing stacked. I am almost there but cannot find what I am missing to only show one div at once. Is there a better way that I could be doing this? Please help?
<div class="row" style="margin-top: 15px;">
<div style="border:1px dashed #CCC;background:#fff;padding:10px 0px;">
<div style="text-align:center;">
<div id="lifehacks" onclick="lhtrial();">
<div id="trialarea">
<p style="background: url('images/LH_Trial.png') 0 0;background-repeat: no-repeat; height: 75px;"> </p>
<p><span id="lhtext"><span style="color:#999; font-size:12px;padding:20px 30px 0 30px;">(Click Above To Opt-In To LifeHacks)</span></span></p>
</div>
<div id="trialarea2">
<p style="background: url('images/LH_Trial.png') 0 -75px;background-repeat: no-repeat; height: 75px;"> </p>
<p><span id="lhtext"><span style="color:#999; font-size:12px;padding:20px 30px 0 30px;">(Click Above If You Want To Opt-Out Of LifeHacks)</span></span></p>
</div>
</div>
</div>
</div>
</div>
Here is my javascript:
<script>
ele = document.getElementById("trialarea");
function lhtrial(){
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "show";
}
else {
ele.style.display = "block";
text.innerHTML = "hide";
}
}
</script>
The following code should work for you, although you are really better off attaching your events using addEventListener() instead of inline in the HTML. You also identified the id lhtext twice in your HTML, which is not allowed.
function lhtrial() {
ele = document.getElementById("trialarea");
ele2 = document.getElementById("trialarea2");
if (ele.style.display === "none") {
ele.style.display = "block";
ele2.style.display = "none";
} else {
ele.style.display = "none";
ele2.style.display = "block";
}
}
#lhimage1 {
background: url('http://lorempixel.com/400/200/sports/1/') 0 0;
background-repeat: no-repeat;
height: 75px;
}
#lhimage2 {
background: url('http://lorempixel.com/400/200/sports/2/') 0 0;
background-repeat: no-repeat;
height: 75px;
}
#trialarea2 {
display: none;
}
<div id="lifehacks" onclick="lhtrial();">
<div id="trialarea">
<p id="lhimage1"> </p>
<p><span id="lhtext1"><span style="color:#999; font-size:12px;padding:20px 30px 0 30px;">(Click Above To Opt-In To LifeHacks)</span></span></p>
</div>
<div id="trialarea2">
<p id="lhimage2"> </p>
<p><span id="lhtext2"><span style="color:#999; font-size:12px;padding:20px 30px 0 30px;">(Click Above If You Want To Opt-Out Of LifeHacks)</span></span></p>
</div>
</div>
function lhtrial(){
ele = document.getElementById("trialarea").style.display;
if(ele == "block") {
document.getElementById("trialarea").style.display = 'none';
document.getElementById("trialarea2").style.display = 'block';
text.innerHTML = "show";
}
else {
document.getElementById("trialarea").style.display = 'block';
document.getElementById("trialarea2").style.display = 'none';
text.innerHTML = "hide";
}
}
<div class="row" style="margin-top: 15px;">
<div style="border:1px dashed #CCC;background:#fff;padding:10px 0px;">
<div style="text-align:center;">
<div id="lifehacks" onclick="lhtrial();">
<div id="trialarea" style="display:block;">
<p style="background: url('images/LH_Trial.png') 0 0;background-repeat: no-repeat; height: 75px;"> </p>
<p><span id="lhtext"><span style="color:#999; font-size:12px;padding:20px 30px 0 30px;">(Click Above To Opt-In To LifeHacks)</span></span></p>
</div>
<div id="trialarea2"style="display:none;">
<p style="background: url('images/LH_Trial.png') 0 -75px;background-repeat: no-repeat; height: 75px;"> </p>
<p><span id="lhtext"><span style="color:#999; font-size:12px;padding:20px 30px 0 30px;">(Click Above If You Want To Opt-Out Of LifeHacks)</span></span></p>
</div>
</div>
</div>
</div>
<button onclick="lhtrial()">button</button><!-- option 2-->
</div>
Test here Solution
I added this <div id="trialarea" style="display:block;"> in html
and little change of js
function lhtrial(){
ele = document.getElementById("trialarea").style.display;
if(ele == "block") {
document.getElementById("trialarea").style.display = 'none';
document.getElementById("trialarea2").style.display = 'block';
text.innerHTML = "show";
}
else {
document.getElementById("trialarea").style.display = 'block';
document.getElementById("trialarea2").style.display = 'none';
text.innerHTML = "hide";
}
}
And i added button but u can set other click event
<button onclick="lhtrial()">button</button>

Keypress not work in Firefox

i have a problem with this javascript.
In firefox i can't delete the content inside the textbox, and i can't select the content with the mouse.
I try to put this version of jquery, but the javascript not works.
(i can edit the textbox, but the effect not appears.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.js"></script>
JavaScript
$('#importo').keypress(function(e){
var key = String.fromCharCode(e.which);
if (isNaN(key)){
return false;
}
}).keyup(function(){
var miglia = $(this).val() * 0.9;
if($('#miglia').length == 0)
{
$(this).after('<span id=\'miglia\' style="margin-left:2px;font-size: 15px; font-family: \'Roboto\', sans-serif; padding-top:6px;letter-spacing: 0px; font-weight:bold;"><img src="world_miglia.png" style="float: left;margin-left: -10px;"> <span style="float: left;color:#000; font-size:15px;font-weight: 400;padding-top: 2px;"> Stai regalando </span>'+ miglia +'miglia <span style="font-family: \'Roboto\', sans-serif; color:#000; font-size:15px;font-weight: 400;">di viaggio!</span></span>');
}
else
{
$('#miglia').html('<img src="world_miglia.png" style="float: left;margin-left: -10px;"> <span style="float: left;color:#000; font-size:15px;font-weight: 400;padding-top: 2px;"> Stai regalando </span>' + miglia + ' miglia <span style="color:#000; font-size:15px;font-weight: 400;">di viaggio!</span>');
}
HTML
<input type="text" name="quota" value="<?=$_SESSION['quota'];?>" id="importo" />

Categories

Resources