Display Selected Check-box data using jquery - javascript

Here i want to display selected check-box text. Help me how to do this
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="../js/jquery_1.9.0.js"></script>
<script type="text/javascript" language="javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
var counter = 1;
var cars = new Array("Paul","Catherine","Steve","Paul","Catherine","Steve","Paul","Catherine","Steve","Paul","Catherine","Steve");
$(document).ready( function() {
$("#checkall").click(function() {
if ($(this).is(':checked')){
$(":checkbox").attr("checked", true);
}
else{
$(":checkbox").attr("checked", false);
}
});
// Uncheck All
for (var i=0;i<cars.length;i++){
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<input type="checkbox" />'+cars[i]+'</br>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
}
});
function checkState(){
var isChecked = $('#checkall').is(':checked');
if(isChecked){
// here i want to display all check-boxes data
} else{
// here i want to display Selected Check-boxes data
}
}
</script>
</head>
<body>
</br>
<div id="TextBoxesGroup">
<div id="TextBoxDiv1">
<input type="checkbox" id="checkall" value="check" />select</br>
<br />
</div>
</div>
<input type = "button" onClick = "checkState()" value = "GetName" id = "button" />
</body>
</html>

Do this to get the names
Changes add checkbox function to (otherwise you won't have any values):
newTextBoxDiv.after().html('<input type="checkbox" value="' + cars[i] + '" />'+cars[i]+'</br>');
Update your if else:
var isChecked = $('[type=checkbox]:checked');
var names = "";
isChecked.each(function(){
names += $(this).val();
});
alert(names);
Live fiddle: http://jsfiddle.net/nyu5T/

Look at jQuery's serialize()
console.log($(":checked").serialize());

I know you have an answer but this addresses several issues: fiddle showing it working:http://jsfiddle.net/WGKuX/
Markup: fix bad html for </br> and remove onclick from markup (in code later)
<br />
<div id="TextBoxesGroup">
<div id="TextBoxDiv1">
<input type="checkbox" id="checkall" value="check" />select
<br />
</div>
</div>
<input type="button" value="GetName" id="button" />
now for some code: comments on each portion
var counter = 1;
var cars = ["Paul", "Catherine", "Steve", "Paul", "Catherine", "Steve", "Paul", "Catherine", "Steve", "Paul", "Catherine", "Steve"]; //change to simpler declaration
$(document).ready(function () {
$("#checkall").click(function () {
$(".myCars").prop("checked", $(this).is(':checked'));
}); // simplify
$("#TextBoxesGroup").on("change", ".myCars", function () {
$("#checkall:checkbox").prop("checked", ($(".myCars").length == $(".myCars:checked").length));
}); // assume "select" means "select all", if all are checked, check the select otherwise uncheck
var mylist = "";
var i = 0;
for (i = 0; i < cars.length; i++) {
mylist += "<div id='TextBoxDiv" + (counter + i) + "'><input class='myCars' type='checkbox' value='" + cars[i] + "' />" + cars[i] + '<br /></div>';
}// note the class added to the checkboxes
$(mylist).appendTo("#TextBoxesGroup"); // simplify the insertion, only hit DOM once
});
$('#button').click(checkState); //event handler moved from markup
function checkState() {
var names = "";
// build list based on the seleck all check state
var checkslist = $('#checkall').prop('checked') ? $('.myCars[type=checkbox]') : $('.myCars[type=checkbox]:checked');
checkslist.each(function () {
names += $(this).val();
});
alert(names);
}

Related

Javascript; html form; user input; display input

I can't figure out why this code won't display the user entered information. I need to have user enter information from the html form, add this info to the arrays, and then display the info (actually, need to do more than this, but can't get past this point). I need the entered information to display on the page. Thanks
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Homework 10</title>
<script type="text/javascript">
//Variables for arrays
var fName = [];
var lName = [];
var tScore = [];
//Variables from user input
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
//Variable for display
var display = document.getElementById("display");
//Function to add user info to arrays
function insert() {
fName.push(fNameInput.value);
lName.push(lNameInput.value);
tScore.push(tScoreInput.value);
clearAndShow();
}
//Function to display info entered from array
function clearAndShow() {
fNameInput.value = "";
lNameInput.value = "";
tScoreInput.value = "";
display.innerHTML = "";
display.innerHTML += "First Name: " + fName.join(", ") + "<br/>";
display.innerHTML += "LastName: " + lName.join(", ") + "<br/>";
display.innerHTML += "Test Score: " + tScore.join(", ") + "<br/>";
}
</script>
</head>
<body bgcolor="Cornsilk">
<h2>Average Student Scores</h2>
<form>
<fieldset>
<legend><strong>Enter First, Last Name and Test Score:</strong></legend><br />
<input type="text" id="firstName" placeholder="First name"/><p />
<input type="text" id="lastName" placeholder="Last name"/><p />
<input type="number" id="testScore" placeholder="Test Score"/><p />
<input type="button" value="Save/Show Average" onclick="insert()"/><p />
</fieldset><p />
</form>
<div id="display"></div>
</body>
</html>
I tried to run the code. I got an error like
test.html:23 Uncaught ReferenceError: fName is not defined
You can solve this by moving the variable declaration inside the function.
//Variables for arrays
var fName = [];
var lName = [];
var tScore = [];
//Function to add user info to arrays
function insert() {
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
fName.push(fNameInput.value);
lName.push(lNameInput.value);
tScore.push(tScoreInput.value);
clearAndShow();
}
//Function to display info entered from array
function clearAndShow() {
var display = document.getElementById("display");
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
fNameInput.value = "";
lNameInput.value = "";
tScoreInput.value = "";
display.innerHTML = "";
display.innerHTML += "First Name: " + fName.join(", ") + "<br/>";
display.innerHTML += "LastName: " + lName.join(", ") + "<br/>";
display.innerHTML += "Test Score: " + tScore.join(", ") + "<br/>";
}
The reason for this is the element is no there when the initial declaration is happening.
Move the script below the body
The main issue is that the Javascript is loaded before the HTML. As a result, when the Javascript attempts to find the element with the element "firstName", it fails to find it because it hasn't been loaded yet.
To fix this, you should move the script tag below the body tag so that the HTML is loaded before it is accessed by the Javascript.
As an added bonus, it improves page load time as the browser doesn't have to wait for the JavaScript to load before rendering the HTML
Example Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Homework 10</title>
</head>
<body bgcolor="Cornsilk">
<h2>Average Student Scores</h2>
<form>
<fieldset>
<legend><strong>Enter First, Last Name and Test Score:</strong></legend><br />
<input type="text" id="firstName" placeholder="First name"/><p />
<input type="text" id="lastName" placeholder="Last name"/><p />
<input type="number" id="testScore" placeholder="Test Score"/><p />
<input type="button" value="Save/Show Average" onclick="insert()"/><p />
</fieldset><p />
</form>
<div id="display"></div>
</body>
<script type="text/javascript">
//Variables for arrays
var fName = [];
var lName = [];
var tScore = [];
//Variables from user input
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
//Variable for display
var display = document.getElementById("display");
//Function to add user info to arrays
function insert() {
fName.push(fNameInput.value);
lName.push(lNameInput.value);
tScore.push(tScoreInput.value);
clearAndShow();
}
//Function to display info entered from array
function clearAndShow() {
fNameInput.value = "";
lNameInput.value = "";
tScoreInput.value = "";
display.innerHTML = "";
display.innerHTML += "First Name: " + fName.join(", ") + "<br/>";
display.innerHTML += "Last Name: " + lName.join(", ") + "<br/>";
display.innerHTML += "Test Score: " + tScore.join(", ") + "<br/>";
}
</script>
</html>

JS - How to add three inputs, get the text from them and show the text in another subpage

I have a problem with adding three input text fields after I put one button.
I'd like to have three new input fields after i push the button "Add author" - these inputs would be: 1. name 2. surname 3. initial. Everyone new input needs to have a different id in order to take the text from the inputs and show it in the new subpage which has to show up right after I push the button "Make the order".
<!DOCTYPE HTML>
<html lang='en'>
<head>
<meta charset='utf-8'>
<link rel='stylesheet' href='css/style.css'>
<script type="text/javascript">
window.onload = Load;
function Load()
{
document.getElementById('add_input').onclick = AddElement;
}
function AddElement()
{
var element = document.createElement('input');
var element2 = document.createElement('input');
var element3 = document.createElement('input');
element.setAttribute('type', 'text');
element.setAttribute('type', 'text');
element.setAttribute('type', 'text');
var number = 0;
var amount = document.forms['add_file'].elements.length;
for (var i = 0; i < ilosc; i++ )
{
if (document.forms['add_file'].elements[i].type == 'text')
{
number += 1;
}
}
element.setAttribute('name', 'file-'+(liczba+1));
element.setAttribute('nazwisko', 'file-'+(liczba+1));
element.style.display = "block";
element.style.margin= "2px";
document.forms['add_file'].appendChild(element);
}
</script>
<!--making order -->
<script>
function getText(){
var publisher = document.getElementById("publisher");
var year = document.getElementById("year");
var div = document.getElementById("readyorder")
div.innerHTML = "("+surname.value+" "+year.value+","+" "+"s."+" "+page.value+")";
}
</script>
</head>
<body>
<div class='container'>
<!-- header -->
<header>
<img src="images/header.jpg" alt=""/>
</header>
<input type="text" name="file-1" />
<input type="text" name="surname-1" />
<input type="submit" value="Add author" id="add_input" />
<form name="add_file" enctype="multipart/form-data" method="post">
</form>
Author's Surname<br>
<input type="text" id="surname"><br>
Page number<br>
<input type="text" id="page"><br>
Year<br>
<input type="text" id="year"><br/>
<input type="submit" value="Make the order" onclick="getText()" /> <br/><br/>
<div id="readyorder"></div><br/>
</body>
</html>
Store your id globaly and increase on each addition.
While Creating your node set their id value using setAttribute
element1.setAttribute('id', 'surname' + number);
Also Create a button while adding textbox's which let you know current order.
var button = document.createElement('input');
Add onclick attribute to call javascript function
button.setAttribute('onclick', 'getText(' + number + ')');
window.onload = Load;
var number = 0;
function Load()
{
document.getElementById('add_input').onclick = AddElement;
}
function AddElement()
{
var element1 = document.createElement('input');
var element2 = document.createElement('input');
var element3 = document.createElement('input');
var label1 = document.createElement('label');
var label2 = document.createElement('label');
var label3 = document.createElement('label');
var button = document.createElement('input');
label1.innerHTML = "</br>Author's Surname " + number + "</br>";
element1.setAttribute('type', 'text');
element1.setAttribute('id', 'surname' + number);
element1.setAttribute('placeholder', 'Surname...');
label1.appendChild(element1);
label2.innerHTML = '</br>Page number ' + number + '</br>';
element2.setAttribute('type', 'text');
element2.setAttribute('id', 'page' + number);
element2.setAttribute('placeholder', 'Page...');
label2.appendChild(element2);
label3.innerHTML = '</br>Year ' + number + '</br>';
element3.setAttribute('type', 'text');
element3.setAttribute('id', 'year' + number);
element3.setAttribute('placeholder', 'Year...');
label3.appendChild(element3);
button.setAttribute('onclick', 'getText(' + number + ')');
button.setAttribute('type', 'button');
button.setAttribute('value', 'Button ' + number);
document.forms['add_file'].appendChild(label1);
document.forms['add_file'].appendChild(label2);
document.forms['add_file'].appendChild(label3);
document.forms['add_file'].appendChild(button);
number++;
}
function getText(id)
{
var surname = document.getElementById("surname" + id);
var page = document.getElementById("page" + id);
var year = document.getElementById("year" + id);
var div = document.getElementById("readyorder")
div.innerHTML = "("+surname.value+" "+year.value+","+" "+"s."+" "+page.value+")";
}
<input type="text" name="file-1" />
<input type="text" name="surname-1" />
<input type="submit" value="Add author" id="add_input" />
<form name="add_file" enctype="multipart/form-data" method="post">
</form>
<hr>
<div id="readyorder"></div><br/>

Get Value in HTML Table using Button

I have a simple table that is populated using an array:
for (var i = 0; i < results.length; i++) {
var object = results[i];
(function($) {
$('#results-table').append('<tbody><tr><td>' + object.get('Name') + '</td><td>' + object.get('Description') + '</td><td><button class="button" onclick="goToClass()">View Class</></tr></tbody>');
})(jQuery);
Ideally I would like the goToClass() function to give me the object.ID for that individual row that was selected.
So for example, if I select the button on the first row in the table it would give me the object.ID for that class.
How would I do this?
Try this:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<table id="results-table">
</table>
</body>
<script>
results = [
{Name:1,Description:"one",ID:1111},
{Name:2,Description:"two",ID:2222},
{Name:3,Description:"Three",ID:3333}
]
for (var i = 0; i < results.length; i++) {
var object = results[i];
(function($) {
$('#results-table').append('<tbody><tr><td>' + object['Name'] + '</td><td>' + object['Description'] + '</td><td><button class="button" onclick="goToClass('+object['ID'].toString()+')">View Class</></tr></tbody>');
})(jQuery);
}
function goToClass(id) {
console.log(id)
}
</script>
</html>
When I click the buttons, the console gives me the correct id in each case.

Add multiple html element dynamically using jquery

I want to add multiple html elements dynamically on button click and get values of each. Also one can delete created element on button click. HTML elements will be textbox and other text box for phone number.
I've tried to create single text box on button click. Fiddle: https://jsfiddle.net/dvkeojqn/
HTML:
<input id="btnAdd" type="button" value="Add" />
<br />
<br />
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnGet" type="button" value="Get Values" />
JS:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAdd").bind("click", function () {
var div = $("<div />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("#btnGet").bind("click", function () {
var values = "";
$("input[name=DynamicTextBox]").each(function () {
values += $(this).val() + "\n";
});
alert(values);
});
$("body").on("click", ".remove", function () {
$(this).closest("div").remove();
});
});
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" type="text" value = "' + value + '" /> ' +
'<input type="button" value="Remove" class="remove" />'
}
</script>
try replacing this function..
$(function () {
$("#btnAdd").bind("click", function () {
var div = $("<div />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("#btnGet").bind("click", function () {
var valuesarr = new Array();
var phonearr = new Array();
$("input[name=DynamicTextBox]").each(function () {
valuesarr.push($(this).val());
});
$("input[name=phoneNum]").each(function () {
phonearr.push($(this).val());
});
alert(valuesarr); alert(phonearr);
});
$("body").on("click", ".remove", function () {
$(this).closest("div").remove();
});
});
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" type="text" value = "' + value + '" /> <input name = "phoneNum" type="text" /> <input type="button" value="Remove" class="remove" />';
}
and HERE is the FIDDLE.
Try to replace this JavaScript code..
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAdd").bind("click", function () {
var div = $("<div />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("#btnGet").bind("click", function () {
var values = "";
$("input[name=DynamicTextBox]").each(function () {
values += $(this).val() + "\n";
});
alert(values);
});
$("body").on("click", ".remove", function () {
$(this).closest("div").remove();
});
});
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" type="text" value = "' + value + '" /> <input name = "DynamicTextBox" type="text" value="'+ value +'" /> <input type="button" value="Remove" class="remove" />';
}
</script>

Passing entered text field value into getJSON string?

I am trying to add some functionality to the entered tags in this image searcher using the flickr API. I have it working but it only works when I write the string within the code. For example I have "cats" in the for now. My goal is the pass the entered value from the textbox (id="textbox1") into the tags in the script above. I want to be able to search from the text box and not go into the code. Thanks for any tips/advice!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>
<head>
<script type="text/javascript" src="jquery-1.11.2.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
$("#button").click(function() {
$("#images").empty();
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "cats",
tagmode: "any",
format: "json"
}, function(data) {
console.log(data);
$.each(data.items, function(i, item) {
$(".buttonclick").remove();
$('<img/>').attr("src", item.media.m).appendTo('#images');
if (i == 1) return false;
});
});
});
$('#images').on('click', 'img', function() {
var $imgClone = $(this).clone().attr('src', $(this).attr('src').replace('_m.', '_b.'));
$('#main').html($imgClone);
});
});
$(document).ready(function() {
var counter = 2;
$("#addButton").click(function() {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label></label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function() {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function() {
var msg = '';
for (i = 1; i < counter; i++) {
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
<h1>Image Search</h1>
<button type="button" id="button">Search</button>
<input type='button' value='Remove Tag' id='removeButton'>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<input type='textbox' id='textbox1'>
<input type='button' value='Add tag' id='addButton'>
</div>
</div>
<div id="images" /></div>
</body>
</html>
In $.getJSON you can switch "cats" with
$("#textbox1").val(),
and it will use the value of the input (whatever the user has typed into it) as the value of "tags".
//Stuff before
tags:$("#textbox1").val(),
//Stuff after
I hope this helped!
Edit:
In case you want to learn more about jQuery's .val(), you can read the documentation here.

Categories