Append not adding item to list [duplicate] - javascript

This question already has answers here:
Clicking a button within a form causes page refresh
(11 answers)
Closed 2 years ago.
Have a simple input box and submit button to append item to list. I have the correct ID’s and selectors. How is set up is you click with “click” function and when it clicks it selects the ul with its id selector then append is used to add the item but nothing appears.
$(document).ready(function() {
$("#somebutton1").click(function() {
$("#someul1").append("<li>Appended item</li>");
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width" />
<title>cfds</title>
<link rel="stylesheet" href="img/bootstrap.min.css" />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<form id="someform1" name="someformname1">
<input id="someinput1" type="text">
<input id="somebutton1" type="submit">
</form>
<br><br>
<div id="somediv1">
<ul id="someul1">
<li>coffee</li>
<li>milk</li>
<li>tea</li>
</ul>
</div>
<br><br>
<script src="https://code.jquery.com/jquery-3.5.0.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
<script src="img/popper.min.js"></script>
<script src="img/bootstrap.min.js"></script>
</body>
</html>

The issue is because the button is in a form and clicking on it submits that form. To have the JS work as you expect you need to stop that form from submitting, which can be done by using a submit event handler and calling preventDefault() on the event which is raised.
In addition you can append the typed value by reading the val() of the field. You can also empty the field after the value is appended. Try this:
jQuery($ => {
let $input = $('#someinput1');
$("#someform1").on('submit', function(e) {
e.preventDefault();
let value = $input.val().trim();
if (value)
$("#someul1").append(`<li>${value}</li>`);
$input.val('');
});
});
<form id="someform1" name="someformname1">
<input id="someinput1" type="text">
<input id="somebutton1" type="submit">
</form><br /><br />
<div id="somediv1">
<ul id="someul1">
<li>coffee</li>
<li>milk</li>
<li>tea</li>
</ul>
</div><br /><br />
<script src="https://code.jquery.com/jquery-3.5.0.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>

Related

trouble loading javascript on html page load from jquery .load()

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>

Input text value into a multiple data list and have option to remove them?

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();
});
});
});

Submitting html form in php

This is my first.php page html part. I have a form including a div and a submit button. I want when button clicked, open a new page (second.php) and display contents of div(id=orderList)
<form id="orderForm" action="second.php">
<div class="col-md-5" id="orderList">
<h3 align="center">Sipariş Listesi</h3>
</div>
<div>
<button type="submit" id="firstConfirmButton" class="btn btn-primary btn-lg">Onayla</button>
</div>
</form>
This is javascript part;
$("#orderForm").submit(function() {
var content = $('#orderList').html();
console.log(content); //(no problem everything is ok)
$('#confirmForm').val(content);
var content2 = $('#confirmForm').html();
console.log(content2); //(it is null)
});
And this is second.php where I want to display the contents in the div(id=confirmForm)
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="script.js"></script>
<META name=viewport content="width=1024, initial-scale=1">
<META http-equiv="Content-Type" content="text/html; charset=utf-8" />
<META HTTP-EQUIV="Content-language" CONTENT="tr">
<link href="shift.css" rel="stylesheet">
<link rel="stylesheet" href="bootstrap.css">
<link rel="stylesheet" href="product.css">
</head>
<body>
<div id="confirmForm"> </div>
</body>
</html>
It doesn't work, what should I change?
If $('#confirmForm') is not an input item you cant access it using $('#confirmForm').val();
your Form is missing method attribute, add POST in method by default its GET
<form id="orderForm" method="post" action="second.php">
Add a <textarea> in first.php inside orderForm to hold the content of #ordelist using jquery and in second page you can get it using $_POST['confirmForm'];
<textarea name="confirmForm" id="confirmForm" cols="30" rows="10"></textarea>
in second page you do this
<div id="confirmForm"> <?php echo $_POST['confirmForm'] ?> </div>
You're trying to put the content in #confirmForm, which isn't present in the first file.
There is no need for JavaScript here. Grab the content of the div using $_['post']
Try this its working :
first.php
<html>
<head>
</head>
<form id="orderForm" action="second.php">
<div class="col-md-5" id="orderList">
<textarea name="confirmForm" id="confirmForm" cols="30" rows="10">Sipari Listesi</textarea>
</div>
<div>
<button type="submit" id="firstConfirmButton" class="btn btn-primary btn-lg">Onayla</button>
</div>
</form>
</html>
second.php
<html>
<body>
<?php
echo $_REQUEST[confirmForm];
?>
</body>
</html>
In addition to what Saqueib said, I think you'll need to make a jQuery change too. I think you're looking for the html() method, not val() because it looks like you're trying to change the displayed HTML, right?

Trouble getting button to show up

I'm new to jQuery and JavaScript. I have a checkbox list that looks great, but I'm trying to add a button to it so that when the user is done checking, the button is hit, and then my function is called to figure out what is checked and also what is not checked.
However, my button is missing. I tried adding the code within li tags with the rest of the checkbox part, but it didn't show up. I tried adding it after the dd tag and also after the end of the div. I think I have to keep it within the form tag for my function to work, unless I'm mistaken. Any ideas why the button isn't showing up?
This is the example I found the function idea in. I searched on the internet and can't find any good ideas why my button doesn't show up. It's probably a syntax error with the tab or something.
Thanks!
This is my code:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>jQuery Michele Project</title>
<link href="css/skins/polaris/polaris.css" rel="stylesheet">
<link href="css/skins/all.css" rel="stylesheet">
<link href="css/demo/css/custom.css" rel="stylesheet">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<script type="text/javascript" src="js/jquery.ui.core.js"></script>
<script type="text/javascript" src="js/jquery.ui.widget.js"></script>
<script src="js/icheck.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.input').iCheck({
checkboxClass:'icheckbox_polaris',
radioClass:'iradio_polaris',
increaseArea:'10%'
});
});
</script>
<script type="text/javascript">
// Returns an array with values of the selected (checked) checkboxes in "frm"
function getSelectedChbox(frm) {
// JavaScript & jQuery Course - http://coursesweb.net/javascript/
var selchbox = []; // array that will store the value of selected checkboxes
// gets all the input tags in frm, and their number
var inpfields = frm.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
// traverse the inpfields elements, and adds the value of selected (checked) checkbox in selchbox
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true) selchbox.push(inpfields[i].value);
}
return selchbox;
}
document.getElementById('btntest').onclick = function() {
var selchb = getSelectedChbox(this.form);
alert(selchb);
}
</script>
<style type="text/css">
ul {list-style-type: none}
img {padding-right: 20px; float:left}
#infolist {width:500px}
</style>
</head>
<body>
<form>
<div class="skin skin-line">
<div class="arrows">
<div class="top" data-to="skin-flat"></div>
<div class="bottom" data-to="skin-polaris"></div>
</div>
</div>
<div class="skin skin-polaris">
<div class="arrows">
<div class="top" data-to="skin-line"></div>
<div class="bottom" data-to="skin-futurico"></div>
</div>
<h3>Select Items for Column Headings</h3>
<dl class="clear">
<dd class="selected">
<div class="skin-section">
<h4>Live</h4>
<ul class="list">
<li>
<input tabindex="21" type="checkbox" id="polaris-checkbox-1">
<label for="polaris-checkbox-1">Checkbox 1</label>
</li>
<li>
<input tabindex="22" type="checkbox" id="polaris-checkbox-2" checked>
<label for="polaris-checkbox-2">Checkbox 2</label>
</li>
<li>
<input type="checkbox" id="polaris-checkbox-3" >
<label for="polaris-checkbox-3">Checkbox 3</label>
</li>
<li>
<input type="checkbox" id="polaris-checkbox-4" checked >
<label for="polaris-checkbox-4">Checkbox 4</label>
</li>
</ul>
</div>
<script>
$(document).ready(function(){
$('.skin-polaris input').iCheck({
checkboxClass: 'icheckbox_polaris',
radioClass: 'iradio_polaris',
increaseArea: '20%'
});
});
</script>
$('#checkbox').prop('checked')
</dd>
</dl>
</div>
<input type="button" value="Click" id="btntest" /> //this button isnt showing up on web page
</form>
</body>
</html>

add content to page from form input - jquery

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();
});
});

Categories