I'm trying to create a simple "to do" app that is built via jquery.
The idea is to have a form input that will accept a string, have that string become a variable that will then be added to a "list" as a new "item." The problem is that these new items (that should appear as new HTML p elements) are not showing up once the Submit button is clicked.
<!DOCTYPE html>
<html>
<head>
<title>To Do</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="style.css" rel="stylesheet" media="screen">
</head>
<body>
<div class="wrapper">
<div class="main">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="jumbotron">
<h1>To Do List</h1>
<form role="form">
<div class="form-group">
<input type="text" class="form-control" id="listInput" placeholder="add items here">
</div>
<div class="button">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
<br/>
<p class="list">
</p>
</div>
</div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="//code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<script src="script.js"></script>
</body>
</html>
JQUERY:
$(document).ready(function(){
$(".button").click(function(){
var add = $('input[name=listInput]').val();
$('.list').append('<p class="item">' + add + '</p>');
});
$(document).on('click','.item', function() {
$(this).remove();
});
});
THE JSFIDDLE IS HERE: http://jsfiddle.net/EUq8P/2/
The problem is the button is a submit button which causes the pages to refresh on click by the default action of the button
Also there is problem with the input field selector, your selector will not work because the input field does not have the name listInput, it has the id listInput, so you need to use id-selector
One solution is to prevent the default action of the button by calling the preventDefault() method of the event
$(document).ready(function () {
$(".button").click(function (e) {
e.preventDefault()
var add = $('#listInput').val();
$('.list').append('<p class="item">' + add + '</p>');
});
$(document).on('click', '.item', function () {
$(this).remove();
});
});
Demo: Fiddle
Another is to change the type of the button from submit to button
Demo: Fiddle
Working demo http://jsfiddle.net/8XfQT/
culprit was: var add = $('input[name=listInput]').val();
it should be var add = $('input[id=listInput]').val();
Hope rest help you out :)
code
$(document).ready(function () {
$(".button").click(function () {
var add = $('input[id=listInput]').val();
$('.list').append('<p class="item">' + add + '</p>');
});
$(document).on('click', '.item', function () {
$(this).remove();
});
});
Related
I created a form using Bootstrap and I need that the outline of inputs of class "partIVAInput" becomes red and that red feedback message appears - not only when input are empty - but also when their value - checked by the "isValidPIVA(value)" function - is wrong.
The handler of "keyup blur change" for the input with class "partIVAInput" checks if the value and assign accordingly the classes "is-valid/invalid" to the input.
<!doctype html>
<html lang="it">
<head>
<!-- Required meta tags -->
<meta charset="ISO-8859-15">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script>
$(function () {
$(".numericInput, .partIVAInput, .capInput").bind("keyup blur change", function (event) {
var value = $(this).val();
if ($(this).hasClass("partIVAInput"))
if (!isValidPIVA(value)) {
$(this).removeClass("is-valid").addClass("is-invalid");
}
else {
$(this).removeClass("is-invalid").addClass("is-valid");
}
});
});
//------------------------------------------------------------------------
function isValidPIVA(value) {
return (value === "123" ? true : false);
}
//------------------------------------------------------------------------
</script>
<title>Test</title>
</head>
<body>
<div class="container">
<form id="frmIscrCant" class="needs-validation" novalidate="">
<div id="divDatiCommittente" class="card bg-light">
<h5 class="card-header">Dati</h5>
<div class="card-body">
<div class="form-row">
<div class="form-group col-md-8">
<label for="tbEnte">Denominazione</label>
<input type="text" id="tbEnte" name="Ente" class="form-control" required="">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="tbPartIvaCommitt">Partita IVA</label>
<input type="text" id="tbPartIvaCommitt" name="PartIvaCommitt" class="form-control partIVAInput" required="">
<div class="invalid-feedback">Inserire una partita IVA valida (123)!</div>
</div>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function () {
'use strict';
window.addEventListener('load', function () {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
Perhaps I'm not handling things well since I'm experiencing the following problem.
When I insert in the field a right value (OK)...
When I insert in the field a wrong value (OK)...
When I submit with a wrong value in the field (NO!!! The feedback message is correctly displayed but the outline of the input has become green while it must be red. Also if I write a new wrong value in the field the outline of the input continues to be green. Further, the form is submitted while with a field marked as "is-invalid" I guess it shouldn't)...
What's wrong?
PS
I created this new thread in replacement of this How can I validate a field using a JavaScript function? that can be closed/deleted.
Working on a personal project with a navigation bar. I am using jquery x.load() to load html pages into a specific div. The pages load correctly into the div. However, one of the is using a jquery flipswitch. I am trying to read the state of this flipswitch, to no prevail. I have a main javascript file that loads the individual pages, which is basically my x.load(). I have a working jquery script for reading the switch state, that works when placed directly into the developers console. I have attempted this code both inline in the individual page as well as my main javascript file. When I place it inside the individual page, it will at times cause a race condition to develop.
I am looking for any suggestions, advice, or direction on being able to read the status of the flipswitch from the individual pages.
The first section of code is my javascript file. The second section of code, is both my individual page, as well as my main html page that loads the individual html page, respectively.
jQuery(document).ready(function() {
var SideNav = $('.side-nav'),
NavTrigger = $('.nav-trigger'),
Content = $('.content'),
ApartmentAlarm = $('#Alarm'),
$('.ui-flipswitch').click(function(){console.log($(this).hasClass('ui-flipswitch-active') ? 'On' : 'Off')})
NavTrigger.on('click', function(event) {
event.preventDefault();
alert("click works");
$([SideNav, NavTrigger]).toggleClass('nav-visible');
});
ApartmentAlarm.on('click', function() {
//event.preventDefault();
Content.load('alarm.html');
$([SideNav, NavTrigger]).toggleClass('nav-visible');
});
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<form>
<label for="LeftSwitch">Left Light:</label>
<input type="checkbox" data-role="flipswitch" name="LeftSwitch" id="LeftSwitch">
<br>
<label for="RightSwitch">Right Light</label>
<input type="checkbox" data-role="flipswitch" name="RightSwitch" id="RightSwitch">
</form>
<script type="text/javascript">
$(document).ready(function() {
console.log('hello');
$('#LeftSwitch').on('flipswitchcreate', function(event, ui) {
alert('me')
});
//$('.ui-flipswitch').click(function(){console.log($(this).hasClass('ui-flipswitch-active') ? 'On' : 'Off')})
})
</script>
</body>
</html>
<html>
<head>
<title>
</title>
<link rel="stylesheet" href="apt.css">
</head>
<body>
<header class="page-header">
<div class="apartment-name">Carlson Casa</div>
<div class="data-top">
<ul class="top-data">
<li>Time</li>
<li>Outside Temp</li>
<li>Inside Temp</li>
<li>Menu<span></span></li>
</ul>
</div>
</header>
<main class="main-content">
<nav class="side-nav">
<ul>
<li>Apartment</li>
<li class="nav-label">Living Room</li>
<li>Alarm control</li>
<li>Chandelier</li>
<li class="nav-label">Bedroom</li>
<li>Lights</li>
<li>Alarm Clock</li>
</ul>
</nav>
<div class="content">
Controls go here
</div>
</main>
<script src="jquery-2.1.4.js"></script>
<script src="main.js"></script>
</body>
</html>
As you are using jQuery Mobile Flipswitch of type checkbox, you can get the status by checking the property checked. Here is a jQuery Mobile Flipswitch playground:
var cases = {false: "Unchecked", true: "Checked"};
function getStatus() {
$("#statusLeft").html(cases[$("#LeftSwitch").prop("checked")]);
$("#statusRight").html(cases[$("#RightSwitch").prop("checked")]);
}
$(document).on("change", "#LeftSwitch", function(e) {
var status = $(this).prop("checked");
$("#statusLeft").html("Changed to "+cases[status]);
});
$(document).on("change", "#RightSwitch", function(e) {
var status = $(this).prop("checked");
$("#statusRight").html("Changed to "+cases[status]);
});
function toggleLeft() {
var status = $("#LeftSwitch").prop("checked");
$("#LeftSwitch").prop("checked", !status).flipswitch("refresh");
}
function toggleRight() {
var status = $("#RightSwitch").prop("checked");
$("#RightSwitch").prop("checked", !status).flipswitch("refresh");
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css">
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<div data-role="page" id="pageone">
<div data-role="content">
<form>
<label for="LeftSwitch">Left Light:</label>
<input type="checkbox" data-role="flipswitch" name="LeftSwitch" id="LeftSwitch">
<span id="statusLeft">Unchecked</span>
<br>
<label for="RightSwitch">Right Light</label>
<input type="checkbox" data-role="flipswitch" name="RightSwitch" id="RightSwitch">
<span id="statusRight">Unchecked</span>
</form>
<button class="ui-btn" onclick="getStatus();">Get Status</button>
<button class="ui-btn" onclick="toggleLeft();">Toggle Left</button>
<button class="ui-btn" onclick="toggleRight();">Toggle Right</button>
</div>
</div>
</body>
</html>
By using the change event instead of click you will be notified of the flipswitch toggling also if you are setting the status in code.
Additional notes:
About what you are defining "race condition" i believe you are referring to one of the common mistakes when using jQuery Mobile, i.e. document.ready vs. page events. Please read this post here, and also take some time to read the whole story in deep in this great post of Omar here: jQuery Mobile “Page” Events – What, Why, Where, When & How? (you will find here some other useful posts about this topic).
Moreover: you are trying to update the flipswtches manually by setting the ui-flipswitch-active class by yourself, but i believe you will run into the problem of keeping the status and the ui consistent. So, you may better use the standard JQM way to set the flipswitch status by using flipswitch.refresh. There is already an example in my code snippet.
The last note: until you strongly need it - and you know how to versioning jQuery Mobile - please use the same version of these libraries in all your files, so in your case i believe the pair jQuery 2.1 + JQM 1.4.5 shall be just fine.
jQuery(document).ready(function() {
var SideNav = $('.side-nav'),
NavTrigger = $('.nav-trigger'),
Content = $('.content'),
ApartmentAlarm = $('#Alarm');
$('.ui-flipswitch').click(function(){console.log($(this).hasClass('ui-flipswitch-active') ? 'On' : 'Off')});
NavTrigger.on('click', function(event) {
event.preventDefault();
alert("click works");
$([SideNav, NavTrigger]).toggleClass('nav-visible');
});
ApartmentAlarm.on('click', function() {
//event.preventDefault();
Content.load('alarm.html');
$([SideNav, NavTrigger]).toggleClass('nav-visible');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<form>
<label for="LeftSwitch">Left Light:</label>
<input type="checkbox" data-role="flipswitch" name="LeftSwitch" id="LeftSwitch">
<br>
<label for="RightSwitch">Right Light</label>
<input type="checkbox" data-role="flipswitch" name="RightSwitch" id="RightSwitch">
</form>
<script type="text/javascript">
$(document).ready(function() {
console.log('hello');
$('#LeftSwitch').on('flipswitchcreate', function(event, ui) {
alert('me')
});
//$('.ui-flipswitch').click(function(){console.log($(this).hasClass('ui-flipswitch-active') ? 'On' : 'Off')})
})
</script>
</body>
</html>
I have an input text box where user enter model number and the model number must be displayed in multiple data lists when user click add button. The user has must also have the option to remove the selected model number in the multiple data lists. I have created the HTML code and Javascript code, but the javascript is not adding.
What is is the best approach to my problem? I'm very newbie to javascript.
Hey is my code:
<html lang=en>
<head>
<title>Add To Datalist</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="bootstrap_3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="bootstrap_3.3.7/fonts/font-awesome.min.css" rel="stylesheet" >
</head>
<body>
<div class="container">
<div class="content">
<br/>
<div class="col-sm-6">
<legend>Compatible Devices </legend>
<input type="text" class="form-control" id="modelNo" name="modelNo" placeholder="Enter Name Here"><br/>
<button class="btn btn-info">Add </button>
<button class="btn btn-danger">Remove</button>
</div>
<div class="col-sm-6">
<div class="listfromPopulatedModelNumber" id="listfromPopulatedModelNumber">
<select id="listfromPopulatedModelNo" multiple="multiple" col=10 rows=10>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
</div>
</body>
JavaScript Code:
<script type="text/javascript">
$(document)
.ready(
function() {
var count = 2;
$("#addModNo")
.click(
function() {
$('#listfromPopulatedModelNo')
.last()
.after(
'#modelNo');
count++;
});
$("#removeModNo").click(function() {
$('#modelNumber > option:selected').remove();
count--;
});
});
</script>
All help will be appreciated.
This should work for you. I have updated solution for you here Updated Solution
$(document).ready(function(){
$('#addModNo').click( function(){
var input = $("input[name='modelNo']").val();
console.log(input);
$('#listfromPopulatedModelNo').append("<option value='"+$(this).val()+"'>"+ input +"</option>");
});
$('#removeModNo').click(function(){
$('option:selected').each( function() {
var input = $("input[name='modelNo']").val();
$('#listfromPopulatedModelNo').append("<option value='"+$(this).val()+"'>"+ input +"</option>");
$(this).remove();
});
});
});
I need to make the letter "x" clickable and ad a function that removes the text that this line below creates.
$("#user").prepend("<li>Hello! <span id='clickable'>x</span></li>");
$(document).ready(function() {
$("#hello").click(function() {
$("#user").prepend("<li>Hello! <span id='clickable'>x</span></li>");
$("#webpage").prepend("<li>Why hello there!!</li>");
$("#user").children("li").first().click(function(){
$(this).remove();
});
$("#webpage").children("li").first().click(function(){
$(this).remove();
});
});
$("#goodbye").click(function() {
$("#user").prepend("<li>Goodbye!</li>");
$("#webpage").prepend("<li>Goodbye, dear user!</li>");
$("#user").children("li").first().click(function(){
$(this).remove();
});
$("#webpage").children("li").first().click(function(){
$(this).remove();
});
});
$("#stop").click(function() {
$("#user").prepend("<li>Stop copying me!</li>");
$("#webpage").prepend("<li>Sorry, i meant no offense.</li>");
$("#user").children("li").first().click(function(){
$(this).remove();
});
$("#webpage").children("li").first().click(function(){
$(this).remove();
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<link href="CSS/bootstrap.css" rel="stylesheet" type="text/css">
<link href="CSS/styles.css" rel="stylesheet" type="text/css">
<script src="jQuery/jQuery.js"></script>
<script src="talk.js"></script>
<title>Talk to the web page</title>
</head>
<body>
<div class="container">
<h1>Talk to the web page</h1>
<p>Click a button to say something to the web page. See what it says back!</p>
<button class="btn btn-primary" id="hello">Say "hello"</button>
<button class="btn btn-inverse" id="goodbye">Say "goodbye"</button>
<button class="btn btn-danger" id="stop">Say "stop copying me!"</button>
<div class="row">
<div class="col-md-6">
<h2>You said:</h2>
<ul class="unstyled" id="user">
</ul>
</div>
<div class="col-md-6">
<h2>The web page said back:</h2>
<ul class="unstyled" id="webpage">
</ul>
</div>
</div>
</div>
</body>
</html>
a clickable letter that removes the text this line above creates.
Create one click event that uses .on (since dynamic content and what not) and remove the parent li element:
$("#user").on("click", "span.clickable", function() {
$(this).parent("li").remove();
});
Also use the class clickable and not the ID (I assume you have more than 1);
I'm trying to update the content of a div (#slide-content) on clicking certain navigation elements (h2.pagenav). The content structure is uniform, and each requested HTML document contains two such nav elements ('Previous','Next'). However, my listener only fires once—for click events on the initial nav button present at page load, and I don't understand why.
My understanding is that when using jQuery's append() function instead of html(), the appended content should be registered with the DOM and thus available for event listening. Lil' help?
The page structure is pretty simple:
The HTML
<?php require('common.php'); ?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Ethogram Lab</title>
<link rel="stylesheet" href="css/foundation.css"/>
<link rel="stylesheet" href="css/foundation-icons.css"/>
<link rel="stylesheet" href="css/app.css"/>
<script src="js/vendor/modernizr.js"></script>
</head>
<body>
<div id="slide-content">
<div class="slide">
<div class="row">
<div class="row">
<!---- content ---->
</div>
<div class="row">
<div class="small-4 small-centered columns">
<h2 data-link="slide_0" class="medium button expand text-center pagenav">Start <i class="fi-play"></i></h2>
</div>
</div>
</div>
</div>
</div>
</div>
<script src='js/vendor/jquery.js'></script>
<script src='js/foundation.min.js'></script>
<script>
$(document).foundation();
</script>
<script src='js/app.js'></script>
</body>
</html>
The Javascript
And here is the relevant it of app.js
/**
* PAGE VARS
*/
var DS = '/';
var WEBROOT = "127.0.0.1"+DS+"ethogram"+DS;
var PHP = ".php";
/**
* DOM LISTENERS
*/
$(".pagenav").click(function() {
console.log("*** pagenav listener has fired");
var loc = $(this).attr('data-link');
var pageNum = loc.substr(-2) == "_" ? loc.substr(-1) : loc.substr(-2);
var URL = WEBROOT+"slides"+DS+loc+PHP;
$.get(URL, function(data) {
$("#slide-content").html('').append(data).fadeIn();
});
});
The ".on()" function should be used. ".live()" is deprecated.
.on() function
$("body").on("click", ".pagenav", function() {
// do something
});
You should use
$("body").on ("click",".pagenav",function(){
// Your code go here
})
This function will detect the items created programatically
See Documentation