I'm trying to develop a dynamic form, where, if the user click on the plus icon, it should create two new fields in the same line.
The code that I have right now, it only create one single field, I tried to duplicate the same code in the funtion, but it only create two fields in vertical position and not in the same line.
Thank you Kindly !
Javascript code
var survey_options = document.getElementById('columna');
var add_more_fields = document.getElementById('add_more_fields');
var remove_fields = document.getElementById('remove_fields');
function Añadir(){
var newField = document.createElement('input');
newField.setAttribute('type','text');
newField.setAttribute('class','form-control');
newField.setAttribute('placeholder','Another Field');
survey_options.appendChild(newField);
}
function Eliminar(){
var input_tags = survey_options.getElementsByTagName('input');
if(input_tags.length > 2) {
survey_options.removeChild(input_tags[(input_tags.length) - 1]);
}
}
Html Code
<!doctype html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<!-- Awsome Fonts-->
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Styling -->
<link rel="stylesheet" type="text/css" href="style.css">
<!-- My Title-->
<title>Hello, world!</title>
</head>
<body>
<form class="Form" id="formulario">
<h1>Factibilidad Técnica y Operativa</h1>
<h2>Análisis de Infraestructura</h2>
<!-- Campos en Columnas-->
<div class="container" id="contenedor">
<div class="row" id="campo">
<div class="col" id="columna">
<input type="text" class="form-control" placeholder="Infraestructura">
</div>
<div class="col" id="columna">
<input type="text" class="form-control" placeholder="Infraestructura">
</div>
</div>
</div>
<!-- Iconos de Agregar / Eliminar Campos-->
<div class="Controls">
<i class="fa fa-plus-square"></i>Añadir
<i class="fa fa-minus-square"></i>Eliminar
</div>
</form>
<!-- JS Script-->
<script src="script.js"></script>
</body>
</html>
Very first point id value must not repeat. It should be unique. For More Info
In html, inputs are embedded in div so you should follow the same in JS to get same result.
div.col-lg-6 makes tags inside them to set half of screen when screen size is large. It will helps to your design
As I said, I created div.col-lg-6.mb-2 in JS and embedded input in div to get final result. mb-2 gives margin-bottom
div is embedded in div#campo and final result is here
var survey_options = document.getElementById('campo');
var add_more_fields = document.getElementById('add_more_fields');
var remove_fields = document.getElementById('remove_fields');
function Añadir(){
var newDiv = document.createElement('div');
newDiv.setAttribute('class', 'col-lg-6 mb-2')
var newField = document.createElement('input');
newField.setAttribute('type','text');
newField.setAttribute('class','form-control');
newField.setAttribute('placeholder','Another Field');
survey_options.appendChild(newDiv)
newDiv.appendChild(newField);
}
function Eliminar(){
var input_tags = survey_options.getElementsByTagName('input');
if(input_tags.length > 2) {
survey_options.removeChild(input_tags[(input_tags.length) - 1]);
}
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<!-- Awsome Fonts-->
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<body>
<form class="Form" id="formulario">
<h1>Factibilidad Técnica y Operativa</h1>
<h2>Análisis de Infraestructura</h2>
<!-- Campos en Columnas-->
<div class="container" id="contenedor">
<div class="row" id="campo">
<div class="col-lg-6 mb-2">
<input type="text" class="form-control" placeholder="Infraestructura">
</div>
<div class="col-lg-6 mb-2">
<input type="text" class="form-control" placeholder="Infraestructura">
</div>
</div>
</div>
<!-- Iconos de Agregar / Eliminar Campos-->
<div class="Controls">
<i class="fa fa-plus-square"></i>Añadir
<i class="fa fa-minus-square"></i>Eliminar
</div>
</form>
</body>
Update
<!-- In HTML -->
<i class="fa fa-plus-square"></i>Añadir
<!-- In Script -->
function createTwoInput(){
Añadir();
Añadir();
}
If any clarification needed, Mention in comment
Related
So, the JavaScript for my project stopped working after including the materialize JavaScript code needed to make my nav bar turn into a hamburger on mobile devices. I've tried placing my file at the bottom of the html, before the navbar script, and after it. Each time is the same, the hamburger and materialize js works but my js file that I'm using for password validation does not.. Here's my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Register Page</title>
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!-- Our own style sheet -->
<link rel="stylesheet" href="style.css">
<!-- For icons -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.sidenav');
var instances = M.Sidenav.init(elems);
});
</script>
</head>
<body>
<nav>
<div class="nav-wrapper">
Logo
<i class="material-icons">menu</i>
<ul class="right hide-on-med-and-down">
<li>Home</li>
<li>About</li>
<li>Register</li>
<li>Contact</li>
</ul>
</div>
</nav>
<ul class="sidenav" id="mobile-demo">
<li>Home</li>
<li>About</li>
<li>Register</li>
<li>Contact</li>
</ul>
<div class="contact-box">
<div class="row">
<form class="col s12">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">account_circle</i>
<input id="icon_prefix" type="text" class="validate">
<label for="icon_prefix">Full Name</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">email</i>
<input id="icon_prefix" type="email" class="validate">
<label for="icon_prefix">Email</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">password</i>
<input id="psw" type="password" name="psw" class="validate" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" required>
<label for="icon_prefix">Password</label>
</div>
<button class="btn waves-effect waves-light" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</div>
</form>
</div>
</div>
ss3
<div id="message">
<h5>Password must contain the following:</h5>
<p id="letter" class="invalid">A <b>lowercase</b> letter</p>
<p id="capital" class="invalid">A <b>capital (uppercase)</b> letter</p>
<p id="number" class="invalid">A <b>number</b></p>
<p id="length" class="invalid">Minimum <b>8 characters</b></p>
</div>
<script type="text/javascript" src="validation.js"></script>
</body>
</html>
And here's the validation.js file:
// Script for validating password. This code was authored by w3schools at the url: https://www.w3schools.com/howto/howto_js_password_validation.asp
var myInput = document.getElementById("psw");
var letter = document.getElementById("letter");
var capital = document.getElementById("capital");
var number = document.getElementById("number");
var length = document.getElementById("length");
// When the user clicks on the password field, show the message box
myInput.onfocus = function() {
document.getElementById("message").style.display = "block";
}
// When the user clicks outside of the password field, hide the message box
myInput.onblur = function() {
document.getElementById("message").style.display = "none";
}
// When the user starts to type something inside the password field
myInput.onkeyup = function() {
// Validate lowercase letters
var lowerCaseLetters = /[a-z]/g;
if(myInput.value.match(lowerCaseLetters)) {
letter.classList.remove("invalid");
letter.classList.add("valid");
} else {
letter.classList.remove("valid");
letter.classList.add("invalid");
}
// Validate capital letters
var upperCaseLetters = /[A-Z]/g;
if(myInput.value.match(upperCaseLetters)) {
capital.classList.remove("invalid");
capital.classList.add("valid");
} else {
capital.classList.remove("valid");
capital.classList.add("invalid");
}
// Validate numbers
var numbers = /[0-9]/g;
if(myInput.value.match(numbers)) {
number.classList.remove("invalid");
number.classList.add("valid");
} else {
number.classList.remove("valid");
number.classList.add("invalid");
}
// Validate length
if(myInput.value.length >= 8) {
length.classList.remove("invalid");
length.classList.add("valid");
} else {
length.classList.remove("valid");
length.classList.add("invalid");
}
}
Am I placing my JavaScript file in the wrong area? I've tried placing it in the body with the same results too. Any help with this would be greatly appreciated :)
Please put your JS file at the end in the <body> tag. like this,
<body>
...
...
<div id="message">
<h5>Password must contain the following:</h5>
<p id="letter" class="invalid">A <b>lowercase</b> letter</p>
<p id="capital" class="invalid">A <b>capital (uppercase)</b> letter</p>
<p id="number" class="invalid">A <b>number</b></p>
<p id="length" class="invalid">Minimum <b>8 characters</b></p>
</div>
...
...
<script>
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.sidenav');
var instances = M.Sidenav.init(elems);
});
</script>
<!-- my own JavaScript file -->
<script type="text/javascript" src="validation.js"></script>
</body>
And also please use a listener in your file to know that the entire document is first loaded so that your code will get the DOM which it is looking for.
window.addEventListener('load', (event) => {
// Script for validating password. This code was authored by w3schools at the url: https://www.w3schools.com/howto/howto_js_password_validation.asp
var myInput = document.getElementById("psw");
var letter = document.getElementById("letter");
var capital = document.getElementById("capital");
...
...
});
You can also use DOMContentLoaded if you are not concerned about the stylesheet loading.
I'm doing a project. At a certain point i want to have two buttons, one for changing to a lighter theme and another to change to a darker theme and apply the changes to the whole website and not just the page in question
This is the page where i have the functionality:
ConfLayout.cshtml:
<!DOCTYPE HTML>
<html>
<head>
<title>TekSell</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="~/Content/styles.css" rel="stylesheet" />
<link href="~/Content/styles-admin.css" rel="stylesheet" />
</head>
<body id="top">
<section id="banner">
<div class="inner">
Learn More
</div>
</section>
<!-- Main1 -->
<div id="main">
<p style="text-align:center">Serviços</p>
<div class="inner">
<!-- Services -->
<div class="thumbnails">
<div class="box">
<img src="~/Content/Images/gallery.jpg" />
<div class="inner">
<h7>Galeria</h7>
</div>
</div>
<div class="box">
<img src="~/Content/Images/location.jpg" />
<div class="inner">
<h7>Localização</h7>
</div>
</div>
</div>
</div>
</div>
<!-- Main2 -->
<div class="page">
<div class="container">
<div class="row">
<div class="col-md-4">
<h3 class="section-title">Sobre Nós</h3>
<figure><img src="~/Content/Images/logo.jpg" /></figure>
<h4>Acerca de nós</h4>
<p>Somos uma empresa fictícia de venda de software informático</p>
</div>
<div class="col-md-4">
<h3 class="section-title">Âmbito</h3>
<h4>Projeto desenvolvido no âmbito da unidade curricular de Laboratório de Desenvolvimento de Software</h4>
</div>
<div class="col-md-4">
<h3 class="section-title">Configurar página</h3>
<h4>Administrador, altere aqui o layout da página</h4>
<div class="dropdown">
<button class="dropbtn">Layout Configuration</button>
<div class="dropdown-content">
Change to lighter theme
Change to darker theme
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Footer -->
<footer id="footer">
<div class="inner">
<h7>TekSell</h7>
<p>Email: teksell#lds.pt</p>
</div>
</footer>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.poptrox.min.js"></script>
<script src="assets/js/skel.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
<script src="~/Scripts/changeLayout.js"></script>
</body>
</html>
As you can see i've two css files created. The 'styles.css' is the lighter theme, and 'styles-admin.css' is the darker theme. The functionality is implemented at "div class="dropdown-content"
What happens is, as i have both css files linked, when i run it, by default, the view assumes the darker theme(styles-admin.css).
This is the javascript file i use to try the changes:
function changeCSS(cssFile, cssLinkIndex) {
var oldlink = document.getElementsByTagName("link").item(cssLinkIndex);
var newlink = document.createElement("link");
newlink.setAttribute("rel", "stylesheet");
newlink.setAttribute("href", cssFile);
document.getElementsByTagName("head").item(cssLinkIndex).replaceChild(newlink, oldlink);
}
What is missing? Am i doing it the wrong way?
If you include two CSS files with the same selectors inside, the second file will always override the first.
Just use one <link> and change its href.
Also, why load jQuery and not use it?
<link href="~/Content/styles.css" rel="stylesheet" />
$("link").attr("href","~/Content/styles-admin.css");
Job done!
Use similar way. Preset the theme colours and change the root attribute like this
const colors =['#317EEB', '#6427BA'];
let index = 0;
function changeBackground(){
index = (index+1)%2;
document.documentElement.style.setProperty('--main-color', colors[index]);
}
:root {
--main-color: #317EEB;
}
.set-background{
background: var(--main-color);
width: 10em;
height: 10em;
}
button{
margin-top: 5px;
}
<div class="set-background">
</div>
<button onClick="changeBackground()">Change color</button>
I'm trying to create a modal activated by jquery. Inside that modal I have a slider created in webflow, but this slider isn't working.
The webflow support suggests to insert, after the modal activator, this line of code: Webflow.require('slider').redraw();
But it's not working.
Here's my code:
$('#plus-1').on('click', function() {
//apri la modal corrispondente
$("#modal-1").css('display', 'flex');
//$('.slider').redraw();
Webflow.require('slider').redraw();
$('#chiudi-1').on('click', function() {
//chiudi la modal corrispondente
$("#modal-1").css('display', 'none');
});});
<script src="https://www.tecmasolutions.com/clients/princype-2/js/configurator-princype-rev002.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://www.tecmasolutions.com/clients/princype-2/css/normalize.css" rel="stylesheet" type="text/css">
<link href="https://www.tecmasolutions.com/clients/princype-2/css/components.css" rel="stylesheet" type="text/css">
<link href="https://www.tecmasolutions.com/clients/princype-2/css/configurator-princype-rev002.css" rel="stylesheet" type="text/css">
<button id="plus-1" type="button">Click Me!</button>
<div id="modal-1" class="modal-prezzi porta-h240 logged">
<div class="info-wrapper-checkout logged">
<a id="chiudi-1" class="chiudi checkout logged">x</a>
<div id="slider-1" class="slider w-slider">
<div class="w-slider-mask">
<div class="img_int-pack-premium-plus a w-slide">
</div>
<div class="img_int-pack-premium-plus b w-slide">
</div>
<div class="img_int-pack-premium-plus c w-slide">
</div>
</div>
<div class="w-slider-arrow-left">
<div class="icon-2 w-icon-slider-left"></div>
</div>
<div class="w-slider-arrow-right">
<div class="icon-3 w-icon-slider-right"></div>
</div>
<div class="slide-nav w-slider-nav w-round"></div>
</div>
</div>
</div>
I found the missing point.
before the Webflow.require('slider').redraw(); I had to put this:
$.fn.redraw = function(){
$(this).each(function(){
var redraw = this.offsetHeight;
});
};
I have two files: index.php and local.js.
This is index.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="../../docs-assets/ico/favicon.png">
<!-- FontAwesome: font-set designed for Bootstrap -->
<link href="css/font-awesome.css" rel="stylesheet">
<title>Befair-Timetracker</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="css/time.css" rel="stylesheet">
<!-- Template HTML to build up a new row on the table -->
<!-- Just for debugging purposes. Don't actually copy this line! -->
<!--[if lt IE 9]><script src="../../docs-assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<body>
<?php
//include("dbconn.php");
?>
<div class="navbar navbar-inverse navbar-fixed-top navbar-time" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle navbarbtn" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Timetracker</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active">Tracking</li>
</ul>
<form class="navbar-form navbar-right">
<div class="form-group">
<input type="text" placeholder="Email" class="form-control input-sm">
</div>
<div class="form-group">
<input type="password" placeholder="Password" class="form-control input-sm">
</div>
<button type="submit" class="btn btn-success">Sign in</button>
</form>
</div><!--/.navbar-collapse -->
</div>
</div>
<!-- Main jumbotron for a primary marketing message or call to action -->
<div class="jumbotron jumbotime">
<div class="container">
<h1 class="time">Timetracker management</h1>
<p class="timepar">Nella tabella sottostante verranno inserite la varie attività, classificabili in base al proprio CH e agli utenti che le svolgono.</p>
<!--<p><a class="btn btn-primary btn-lg" role="button">Learn more »</a></p>-->
</div>
</div>
<div class="container">
<h3 class="time">Risultati attesi</h3>
<hr>
<div class="selection"> <!-- inserire well nella classe per ottenere riquadro blu -->
<span class="titolosel">Centro di costo</span>
<select class="form-control selecttime">
</select>
</div>
<hr>
<!-- Table containing the info about CH, users and RA -->
<table id ="timetable" class="table table-striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Users</th>
<th>Activities</th>
<th>Timer</th>
</tr>
</thead>
<tbody class="ra hide">
</tbody>
</table>
<footer>
© BeFair 2013 - Website developed by Riccardo Pancotti
<div class="pull-right">
<!--<img src="images/beFair.jpg" alt="beFair-logo" class="img-rounded imglogo">-->
</div>
</footer>
</div> <!-- /container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/bootstrap.js"></script>
<script type="text/javascript" src="js/jquery.tmpl.min.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.min.js"></script>
<script type="text/javascript" src="js/local.js"></script>
<script type="text/javascript" charset="utf-8">
//**ANIMATED DIV/TABLE/TIMER**
function showact(ID){
$(".tr-act"+ID).animate({"height": "toggle"}, { duration: 300 });
//$(".hide").animate({"display":"toggle"}, { duration: 300 });
}
</script>
<script type="text/javascript" charset="utf-8">
//**LOADING JSON**
$(document).ready(function()
{
starttimer(2);
$.getJSON('js/test2.json', function(json) {
$.each(json.ch,function(key,val)
{
var chname=("<option value="+val.name+">"+val.name+"</option>");
$(".selecttime").append(chname);
});
});
});
</script>
<script type="text/javascript" charset="utf-8">
//$(document).ready(startimer(4));
//**CENTRO DI COSTO SELECTION**
$('.selecttime').change(function()
{
var pippo = "";
console.clear();
//setValue();
var pippo = $('.selecttime').val();
var chtable=("<tbody class=\"ra\"><tr>");
$.ajaxSetup( { "async": false } ); //Chiamata asincrona al server per il JSON
$.getJSON('js/test3.json', pippo,function(json) {
for (var i = 0, len = json.ch.length; i < len; i++) {
var namera = json.ch[i].name;
console.log(namera);
if (pippo === namera)
{
console.log("RA " +json.ch[i].ra_list.length);
for (var k = 0, lungh = json.ch[i].ra_list.length; k < lungh; k++)
{
//CICLO PER AGGIUNGERE NUOVE RA
var print = json.ch[i].ra_list[k];
chtable +=("<td>"+print.id+"</td>");
chtable +=("<td>"+print.name+"</td>");
chtable +=("<td>"+print.users+"</td>");
//***VECCHIA RIGA, MOSTRA TIMER***
//chtable +="<td><i class=\"fa fa-plus-square\"></i></td>";
//********************************
chtable +="<td class=\"timertd\"><i class=\"fa fa-plus-square\">+</i></td>";
chtable +="<td></td>";
console.log("Attività " + print.activities.length);
tract = "";
list_act = "";
count = 0;
for (var j = 0, lungh_in = json.ch[i].ra_list[k].activities.length; j < lungh_in; j++)
{
//CICLO PER AGGIUNGERE NUOVE ATTIVITA'
list_act += ("<tr style=\"display:none\" class=\"tr-act"+k+"\">");
list_act += "<td></td><td></td><td></td>";
list_act += "<td>";
list_act += print.activities[j].name;
list_act += "</td>";
list_act += "<td>" + "setValue()" + "</td>";
list_act += ("</tr>");
count++;
}
chtable += list_act;
chtable += "</tr>";
$(".ra").replaceWith(chtable);
}
}
}
});
});
</script>
</body>
</html>
And this is local.js:
var starttimer = function(idt)
{
alert(idt);
};
I'm trying to call this function here (it's part of the index.html):
<script type="text/javascript" charset="utf-8">
//**LOADING JSON**
$(document).ready(function()
{
starttimer(2);
$.getJSON('js/test2.json', function(json) {
$.each(json.ch,function(key,val)
{
var chname=("<option value="+val.name+">"+val.name+"</option>");
$(".selecttime").append(chname);
});
});
});
</script>
but it keeps telling me "function is not defined".
What's the problem?
Probably it's something about the scope but i don't know what.
Solved, i was refering to the wrong file.
OK, so here's my issue (it must be simple, but I still cannot figure this one out)...
I've got a sample HTML code like the one below :
<!-- New Website #1 -->
<!DOCTYPE html>
<html style='min-height:0px;'>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1">
<link rel="stylesheet" href="jquery.mobile.min.css" />
<link rel="stylesheet" href="custom.css" />
<link rel="stylesheet" href="dev.css" />
</head>
<body id="jqm-website-6926" class="" >
<!-- New Page #1 -->
<div data-role="page" comp-id="jqm-page-6271" id="jqm-page-6271" class="" data-add-back-btn="false" data-back-btn-text="" data-back-btn-theme="" data-dom-cache="false" data-theme="" data-title="" >
<!-- New Header #1 -->
<div data-role="header" comp-id="jqm-header-364" id="jqm-header-364" class="" data-position="" data-fullscreen="false" data-theme="" >
<h1></h1>
</div>
<!-- / New Header #1 -->
<!-- New Content #1 -->
<div data-role="content" comp-id="jqm-content-3537" id="jqm-content-3537" class="" data-theme="" >
<!-- New Button #1 -->
<div comp-id="jqm-button-1547" >
<a data-role="button" id="jqm-button-1547" class="" data-corners="true" data-icon="" data-iconpos="left" data-iconshadow="true" data-inline="false" data-mini="false" data-shadow="true" data-theme="" href="#" data-transition="(null)">
</a>
</div>
<!-- / New Button #1 -->
</div>
<!-- / New Content #1 -->
</div>
<!-- / New Page #1 -->
<!-- New Page #1 -->
<div data-role="page" comp-id="jqm-page-9207" id="jqm-page-9207" class="" data-add-back-btn="false" data-back-btn-text="" data-back-btn-theme="" data-dom-cache="false" data-theme="" data-title="" >
</div>
<!-- / New Page #1 -->
<script src="jquery.min.js"></script>
<script src="jquery.mobile.min.js"></script>
<script src="custom.js"></script>
<script src="dev.js"></script>
</body>
</html>
<!-- / New Website #1 -->
All I want to do is when a specific element, with the comp-id attribute set, is clicked - we highlight (by adding the msp-selected class) just that specific element.
However, this is not working...
This is what I've tried :
function removeAll()
{
$("[comp-id]").each(function() {
if ($(this)!==undefined) {
$(this).removeClass("msp-selected");
}
});
}
$(document).ready( function() {
$('[comp-id]:not(.msp-selected)').on('click', function(e) {
removeAll();
$(this).addClass('msp-selected');
});
});
However, here's the problem :
When clicking on the button (comp-id="jqm-button-1547")
It highlights : a) first the button, b) then jqm-content-3537, c) then jqm-page-6271
In a few words, in the end, the 'page' is highlighted, instead of the button.
Any ideas?
And here's a fiddle : http://jsfiddle.net/CTZD3/
Maybe you can stop the event to be propagated to parents elements with event.stopPropagation();
$(document).ready( function() {
$('[comp-id]:not(.msp-selected)').on('click', function(e) {
removeAll();
e.stopPropagation();
$(this).addClass('msp-selected');
});
});