How to catch text into input textbox value jquery - javascript

In below code i have appended list of groups, if i clicked on any group, a model box will be opened. i need to edit list of values from textbox.. in my code if i clicked on any group.. the data is showing same in modal box.. but i need to show data in modal box in input textboxes..
DEMO
$(document).ready(function() {
var $appendItemsToList;
$("#btn2").click(function() {
var text = $('#newCheckText').val();
$("#oo", $appendItemsToList).append('<input type="checkbox" /> ' + text + '<br />');
$("#ol").append("<input type='text' value=" + text + "><br />");
});
$("#add_list").on('click', function() {
$("#list_group").append("<div class=" + 'opener' + "><h2>List (//click)</h2><div id=" + 'oo' + "><input type='checkbox' /><span>List item 1</span><br/><input type='checkbox' /><span>List item 2</span><br/><input type='checkbox' /><span>List item 3</span><br/></div></div>");
});
$("#dialog").dialog({
autoOpen: false,
});
$(document).on('click', '.opener', function() {
$appendItemsToList = $(this);
$("#dialog").dialog("open");
$("#ol").html($('#oo', $appendItemsToList).html());
});
});
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<button id="add_list">add list</button>
<div id="dialog" title="Add List">
<h2>List items</h2>
<div id="ol">
<input value="List item 1">
<br/>
<input value="List item 2">
<br/>
<input value="List item 3">
<br/>
</div>
<div id="oo"></div>
<input type="text" id="newCheckText" value="enter" />
<button id="btn2">Add</button>
</div>
<div id="list_group">
<div class="opener">
<h2>List (//click)</h2>
<div id="oo">
<input type="checkbox" /><span>List item 1</span>
<br/>
<input type="checkbox" /><span>List item 2</span>
<br/>
<input type="checkbox" /><span>List item 3</span>
<br/>
</div>
</div>
</div>

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<style>
</style>
<script>
$(document).ready(function() {
//to add default list
addList();
$("#dialogWindow").dialog({
autoOpen: false,
});
});
function addList(){
var count = $(".listGroup").children().length;
var $tempRow = $(".blankListItem").last().clone();
$tempRow.attr("class", "listItem");
$tempRow.attr('index', count);
$tempRow.show();
$(".listGroup").append($tempRow);
}
function addItem(){
var text = $("#newCheckText").val();
$("#dialogWindow").find("#items").append("<input type='text' value='" + text +"' /> </br>");
$("#newCheckText").val("Enter Value");
var index = $("#dialogWindow").attr("index");
var currentList =$(".listGroup").find(".listItem").eq(parseInt(index));
$(currentList).find(".list").append("<input type='checkbox' class='chk1' /> <label class='label1' >" + text +" </label></br>");
}
function openModalWindow(source){
var index = $(source).attr('index');
var itemCount = $(source).find('input[type="checkbox"]').length;
$("#dialogWindow").find("#items").empty();
for(var i=0; i< itemCount; i++){
var text = $(source).find("[class^='label']").eq(i).text();
$("#dialogWindow").find("#items").append("<input type='text' value='" + text +"' /> </br>");
}
$("#dialogWindow").attr("index", index);
$("#dialogWindow").dialog("open");
}
</script>
</head>
<body >
<button id="btnAddList" onclick="addList()">Add List</button>
<div id="dialogWindow" title="Add List" index="0">
<h2>List items</h2>
</br>
<div id="items">
</div>
<input type="text" id="newCheckText" value="Enter Value" />
<button id="btnAddItem" onclick="addItem()">Add</button>
</div>
<div class="listGroup">
</div>
<div class="blankListItem" style='display:none;' onclick="openModalWindow(this)">
<h2>List (//click)</h2>
<div class="list">
<input type="checkbox" class='chk1' index="0"/> <label class='label1' index="0" >List Item 1 </label>
<br/>
<input type="checkbox" class='chk1'index="1"/> <label class='label1' index="1">List Item 2 </label>
<br/>
<input type="checkbox" class='chk1' index="2"/> <label class='label1' index="2">List Item 3 </label>
<br/>
</div>
</div>
</body>
</html>

Change the Opener click event code to below
$(document).on('click', '.opener', function() {
$appendItemsToList = $(this);
$("#ol").empty();
$appendItemsToList.find('input[type="checkbox"]').each( function(i){
var value = "List Item "+ i;
$("#ol").append('<input type="text" value="'+value+'" />');
});
$("#dialog").dialog("open");
});

Related

jQuery - Assign the click function to the radio input

What I would like to do is assign both the checked value and the click function to the radio input located inside the parent div.
I currently have this code but it only works for assigning the checked value. The click () function does not work:
<div id="contPosition">
<div class="contPosition">
<input type="radio" class="posPrint1" />
</div>
<div class="contPosition">
<input type="radio" class="posPrint2" />
</div>
<div class="contPosition">
<input type="radio" class="posPrint3" />
</div>
</div>
</div>
</div>
<div id="contPrintPosition">
<div class="contPrintPosition">
<input type="radio" class="posPrint1" />
</div>
<div class="contPrintPosition">
<input type="radio" class="posPrint2" />
</div>
<div class="contPrintPosition">
<input type="radio" class="posPrint3" />
</div>
</div>
</div>
</div>
<script>
jQuery('.contPosition').click(function () {
var val = $(this).find('input:radio').prop('checked')?false:true;
$(this).find('input:radio').prop('checked', val);
});
//THIS FUNCTION DOES NOT WORK AS EXPECTED
jQuery('.contPosition input').click(function(){
var curCls = $(this).attr('class');
$(`.contPrintPosition > input.${curCls}`).val("Test");
});
//THIS FUNCTION DOES NOT WORK AS EXPECTED
jQuery('.contPosition input[type=radio]').click(function(){
if (this.previous) {
this.checked = false;
}
this.previous = this.checked;
});
</script>
I dont know what you want to achieve exactly but only one click event could replace all the other event as below snippet :
$(function() {
//should be ".contPosition input[type=radio]"
$('.contPosition input[type=radio]').click(function(e) {
var curCls = $(this).attr('class');
$(`.contPrintPosition > input.${curCls}`).val("Test");
if (this.previous) {
this.checked = false;
}
this.previous = this.checked;
});
})
.contPrintPosition input::after {
content: attr(value);
width:100%;
margin-left:15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="contPosition">
<div class="contPosition">
<input type="radio" class="posPrint1" />
</div>
<div class="contPosition">
<input type="radio" class="posPrint2" />
</div>
<div class="contPosition">
<input type="radio" class="posPrint3" />
</div>
</div>
<div id="contPrintPosition">
<div class="contPrintPosition">
<input type="radio" class="posPrint1" />
</div>
<div class="contPrintPosition">
<input type="radio" class="posPrint2" />
</div>
<div class="contPrintPosition">
<input type="radio" class="posPrint3" />
</div>
</div>

Apply to everyone with checkbox

I record meals in this way, as I show in the image:
I created the Apply to All button, which is to fill the remaining days of the month with the same data after completing the 1st of the month. For example:
I pre-pack the day 1:
By clicking the Apply to All button fill the remaining days in the same way:
Code:
<input type='button' id='elemento' value='Aplicar a Todos' />
<td bgcolor='$color' data-semana=''><font size='2px'/>
<input id='firstCB{$year}{$month}{$day}' type='checkbox' name='arrachar[$year, $month, $day][dia]' value='$year-$month-$day'>$year-$month-$day <br />
<div>
<input type='checkbox' class='checkbox' name='arrachar[$year, $month, $day][OpcaoA]' value='Peq_Almoço'>Peq. Almoço</div> <div><input ref='firstCB{$year}{$month}{$day}' min='0' oninput='this.value = Math.abs(this.value)' type='number' name='arrachar[$year, $month, $day][Qtd]' value='$marcado_pequeno_qtd' />
<br />
</div>
<div>
<input type='checkbox' class='checkbox1' name='arrachar[$year, $month, $day][opcaoB]' value='Almoço'>Almoço</div> <div><input ref='firstCB{$year}{$month}{$day}' min='0' oninput='this.value = Math.abs(this.value)' type='number' name='arrachar[$year, $month, $day][Qtd1]' value='$marcado_almoco_qtd'/>
<br />
</div>
</td>
Javascript:
$('#elemento').on('click', function(){
var inputs = [...document.querySelectorAll("[type='checkbox']")];
if(inputs == 'checked'){ // condição
$('.checkbox').prop('checked', true);
$('.checkbox1').prop('checked', true);
}
});
I wanted you to select all the checkboxes on every day as on day 1 and also fill in the inputs with the same value as day 1.
As I have the condition does not select any checkbox when clicking the Apply to all button.
I know you are using JQuery, but heres an option in vanilla JS. Talvez te servia melhor. Portugal Ale!
const dayChecks = document.querySelectorAll('.day input[type="checkbox"]');
const dayInputs = document.querySelectorAll('.day input[type="number"]');
const btn = document.querySelector('#click');
btn.addEventListener('click', () => {
dayChecks.forEach( input => { // Handles checkboxes
if(input.checked){
const elClass = input.parentElement.getAttribute('class');
const allEls = document.querySelectorAll(`.${elClass}`);
allEls.forEach( (el) => {
el.querySelector('input[type="checkbox"]').setAttribute('checked', 'checked');
});
}
});
dayInputs.forEach( input => { // Handles Inputs
if(input.value != ''){
const value = input.value;
const elClass = input.parentElement.getAttribute('class');
const allEls = document.querySelectorAll(`.${elClass}`);
allEls.forEach( (el) => {
el.querySelector('input[type="number"]').value = value;
});
}
});
});
.week {
display: flex;
flex-direction: row;
}
.day{
padding: 20px;
}
<button id='click'>Apply to All</button>
<div class="week">
<div class="day">
<h2>Primeiro Dia</h2>
<div class="peqAlmoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="almoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="jantar">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
</div>
<div class="day">
<h2>Segundo Dia</h2>
<div class="peqAlmoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="almoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="jantar">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
</div>
<div class="day">
<h2>Terçeiro Dia</h2>
<div class="peqAlmoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="almoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="jantar">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
</div>
</div>
If you want an elegant JQuery implementation try this:
$(document).ready(function(){
// used the first checkbox (input with the date class) to select each data column for entering data
// this is the column you want replicated on other columns
$('.date').change(function() {
// inactivate every other column that is not this column
$('.date').not($(this)).prop('checked', false).parents('td').removeClass('active');
// show that this is the currently selected column
$(this).parents('td').toggleClass('active');
});
// click handler for 'apply to all' button
$('#elemento').click(function() {
var checkboxstate = {}; // object to store all the checkbox state in the current column
var numberstate = {}; // object to store content of all text input in the current column
// for each input element in the active column
$.each($('.active').find('input'), function(key, element){
if($(this).prop('type') == 'checkbox') {
// collect all checkbox state
checkboxstate[element.name] = $(this).prop('checked');
} else {
// collect all input text content
numberstate[element.name] = $(this).val();
}
});
// for each checkbox or number
$.each($('.checkbox, .number'), function(key, element) {
// store these variables beforehand so you don't need to test for them in the inner each statement
// for checkboxes
var target = checkboxstate;
var type = 'checkbox';
var property = 'checked';
// for number elements
if($(this).is('.number')) {
target = numberstate;
type = 'number';
property = 'value';
}
// assign object properties to dom elements with same type and name properties as that of the object property
$.each(target, function(key_1, element_1) {
if($(element).prop('type') == type && $(element).prop('name') == key_1) {
$(element).prop(property, element_1);
}
});
});
return false;
});
});
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="index.js"></script>
<title>My test doc</title>
<style>
table {
border-collapse: collapse;
}
.active {
background-color: #00ff00;
}
input {
margin-bottom: 5px;
}
.checkbox-div {
float: left;
}
.number-div {
float: right;
margin-left: 10px;
}
</style>
</head>
<body>
<h3>welcome</h3>
<form method="GET" action="#">
<table style="border-collapse: collapse">
<tr>
<td>
<input class="date" type='checkbox' name='date' value='date'>Date
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Peq_Almoço' value='Peq_Almoço'>Peq. Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Peq_Almoço' value='' />
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Almoço' value='Almoço'>Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Almoço' value=''/>
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Lanche' value='Lanche'>Lanche
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Lanche' value=''/>
</div>
<br/>
</td>
<td>
<input class="date" type='checkbox' name='date' value='date'>Date
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Peq_Almoço' value='Peq_Almoço'>Peq. Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Peq_Almoço' value='' />
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Almoço' value='Almoço'>Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Almoço' value=''/>
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Lanche' value='Lanche'>Lanche
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Lanche' value=''/>
</div>
<br/>
</td>
</tr>
<tr>
<td>
<input class="date" type='checkbox' name='date' value='date'>Date
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Peq_Almoço' value='Peq_Almoço'>Peq. Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Peq_Almoço' value='' />
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Almoço' value='Almoço'>Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Almoço' value=''/>
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Lanche' value='Lanche'>Lanche
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Lanche' value=''/>
</div>
<br/>
</td>
</tr>
</table>
<input type='button' id='elemento' value='Aplicar a Todos' />
</form>
</body>
</html>
Also see the Fiddle sample here
Here, each column is represented by a td element. I used the first checkbox with the date class to select the column we want other columns to replicate.
Also, the checkbox and number inputs are loosed coupled - that is, a checkbox can be unchecked with the corresponding number input filled and this will still be replicated on other columns.
Three columns were used for brevity. You can create as many columns as you want and the jQuery script will still run seamlessly.
You can apply classes to each checkbox and select all checkbox on click of Apply to All button
<input type="checkbox" class="Almoco" />
$('#elemento').on('click', function(){
if(check for your condition if you need to apply check for all checkboxes)
{
$('.Almoco').prop('checked', true);
}
//Similiarily check for other checkboxes
});
Your variable inputs is a collection of inputs, therefore you have to check the state of each input in a forEach or a for loop.
Same for other inputs that you want to modify the state.
Code:
$('#elemento').on('click', function(){
var inputs = $('td > input');
inputs.each(function(index, element){
if(element.checked) {
var children = $(element).parent().find('input[type="checkbox"]');
children.each(function(i, child){
$(child).prop('checked', true);
});
}
});
});
I was able to solve the problem of applying to everyone in the following way:
$('#elemento').click(function() {
var checkedValues = Array(8).fill(false);
var textValues = Array(7).fill('');
var checkedStep = 0;
var textStep = 0;
$('tr').find('input[type="checkbox"]').each(function(index, value){
if(index < 8){
checkedValues[index] = $(this).prop("checked");
}else{
if(checkedStep == 8){
checkedStep = 0;
}
$(this).prop('checked', checkedValues[checkedStep++]);
}
});
$('tr').find('input[type="number"]').each(function(index, value){
if(index < 7){
textValues[index] = $(this).val();
}else{
if(textStep == 7){
textStep = 0;
}
$(this).val(textValues[textStep++]);
}
});
});

Remove appended data on second click

I have few checkboxes. When I click on any of them I pass the value to span. Everything seems to work fine but there's something that I can't resolve. When I click first time value is passed to my span (checkbox is checked) but when I unclick this checkbox, value is passing to span again instead of delete it from my span. Next thing, when I want to write my own text I have other checkbox for that. When I click on it I see input. I cant write text and it will be appended to my span. I want to remove this value too when I unclick this checkbox. Last thing, I want to add red border to empty elements. Anyone could help me?
$('.checkbox').on('click', function(){
var dataAttr = $(this).attr('name');
var dataAttrVal = $(this).val();
$('[name="' + dataAttr + '-value"]').append(dataAttrVal + ", ");
$('#summary_' + dataAttr).append(dataAttrVal + ", ");
});
$('.component-other-value').on('change touchstart tap', function(){
var dataName = $(this).attr('data-product');
var value = $(this).val();
$('#summary_other_' + dataName).text(value);
$('[name="' + dataName + '-value"]').append(value + ", ");
});
$('.component-other').on('click', function(){
$(this).closest('.container')
.find('.component-other-value')
.prop("disabled", !this.checked);
});
input:disabled {
opacity: 0;
}
input:enabled {
opacity: 1;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruit-pineapple" value="Ananas" class="fruits checkbox">
<label for="fruit-pineapple"><img src="img/ananas.png"></label>
<p class="description">Ananas</p>
</div>
</div>
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruit-apple" value="Jabłko" class="fruits checkbox">
<label for="fruit-apple"><img src="img/jablko.png"></label>
<p class="description">Jabłko</p>
</div>
</div>
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruits-oth" class="component-other">
<label for="fruits-oth"><img src="img/owoce-wlasne.png"></label>
<p class="description">Własna propozycja</p>
</div>
</div>
<input type="text" name="fruits-other" id="fruits-other" class="component-other-value" data-product="fruits" placeholder="Wpisz owoce" disabled>
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruit-nofruit" value="Bez owoców" class="fruits checkbox">
<label for="fruit-nofruit"><img src="img/owoce-brak.png"></label>
<p class="description">Bez owoców</p>
</div>
</div>
</div>
<p>
Owoce: <br>
<span id="summary_fruits" class="summary"></span>
<span id="summary_other_fruits" class="summary" style="border-bottom: 1px solid red;"></span>
</p>
</div>
check whether the event is fired when the checkbox is checked or not checked.
$('.checkbox').on('click', function(){
if($(this).is(':checked')){
//do you logic when the checkbox is checked.
}else{
//do your logic when the checkbox is not checked.
}
});
You need to loop over all checkboxes when each checkbox is clicked
Note I wrapped the whole thing in the label.
$('.component-other-value, .fruits').on('change', function() {
var fruits = [], other = [];
$('.component-other-value, .fruits').each(function() {
if (this.checked) {
var dataName = $(this).attr('data-product');
var value = $(this).val();
if (dataName) other.push(value)
else fruits.push(value)
}
});
$('#summary_fruits').text(fruits.join(","));
$('#summary_other_fruits').text(other.join(","));
});
$('.component-other').on('click', function() {
$(this).closest('.container')
.find('.component-other-value')
.prop("disabled", !this.checked);
});
input:disabled {
opacity: 0;
}
input:enabled {
opacity: 1;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-3">
<div class="input-item">
<label>
<input type="checkbox" name="fruits" id="fruit-pineapple" value="Ananas" class="fruits checkbox">
<img src="img/ananas.png">
<p class="description">Ananas</p>
</label>
</div>
</div>
<div class="col-sm-3">
<div class="input-item">
<label>
<input type="checkbox" name="fruits" id="fruit-apple" value="Jabłko" class="fruits checkbox">
<img src="img/jablko.png">
<p class="description">Jabłko</p>
</label>
</div>
</div>
<div class="col-sm-3">
<div class="input-item">
<label>
<input type="checkbox" name="fruits" id="fruits-oth" class="component-other">
<img src="img/owoce-wlasne.png">
<p class="description">Własna propozycja</p>
</label>
</div>
</div>
<input type="text" name="fruits-other" id="fruits-other" class="component-other-value" data-product="fruits" placeholder="Wpisz owoce" disabled>
<div class="col-sm-3">
<div class="input-item">
<label>
<input type="checkbox" name="fruits" id="fruit-nofruit" value="Bez owoców" class="fruits checkbox">
<img src="img/owoce-brak.png">
<p class="description">Bez owoców</p>
</label>
</div>
</div>
</div>
<p>
Owoce: <br>
<span id="summary_fruits" class="summary"></span>
<span id="summary_other_fruits" class="summary" style="border-bottom: 1px solid red;"></span>
</p>
</div>
$('.checkbox').on('click', function(){
var check = $(this);//PROPERTIES OF CLICKED CHECKBOX
var dataAttr = $(this).attr('name');
var dataAttrVal = $(this).val();
if (check.prop('checked')==true){ // check weather checkbox is checked.
$('[name="' + dataAttr + '-value"]').append(dataAttrVal + ", ");
$('#summary_' + dataAttr).append(dataAttrVal + ", ");
}
else { //if not remove the occurence of value that you unchecked
str = $('#summary_' + dataAttr).html();
$('#summary_' + dataAttr).html(str.replace(dataAttrVal+", ",""));
}
});
$('.component-other-value').on('change touchstart tap', function(){
var dataName = $(this).attr('data-product');
var value = $(this).val();
$('#summary_other_' + dataName).text(value);
$('[name="' + dataName + '-value"]').append(value + ", ");
});
$('.component-other').on('click', function(){
$(this).closest('.container')
.find('.component-other-value')
.prop("disabled", !this.checked);
});
input:disabled {
opacity: 0;
}
input:enabled {
opacity: 1;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruit-pineapple" value="Ananas" class="fruits checkbox">
<label for="fruit-pineapple"><img src="img/ananas.png"></label>
<p class="description">Ananas</p>
</div>
</div>
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruit-apple" value="Jabłko" class="fruits checkbox">
<label for="fruit-apple"><img src="img/jablko.png"></label>
<p class="description">Jabłko</p>
</div>
</div>
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruits-oth" class="component-other">
<label for="fruits-oth"><img src="img/owoce-wlasne.png"></label>
<p class="description">Własna propozycja</p>
</div>
</div>
<input type="text" name="fruits-other" id="fruits-other" class="component-other-value" data-product="fruits" placeholder="Wpisz owoce" disabled>
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruit-nofruit" value="Bez owoców" class="fruits checkbox">
<label for="fruit-nofruit"><img src="img/owoce-brak.png"></label>
<p class="description">Bez owoców</p>
</div>
</div>
</div>
<p>
Owoce: <br>
<span id="summary_fruits" class="summary"></span>
<span id="summary_other_fruits" class="summary" style="border-bottom: 1px solid red;"></span>
</p>
</div>

Jquery, for loop shows all

$("#button").click(function () {
var pp = []
var ing = []
for (var q = 1; q <= 6; q++) {
pp[q - 1] = $('input[name=P' + (q) + ']').is(":checked");
ing[q - 1] = $('div#ingp' + (q) + '').show();
}
for (var q = 1; q <= 6; q++) {
if (pp[q - 1] == true) {
ing[q - 1];
}
}
});
<div class="Pizzas container" id="checkbox_pizza">
<h1>Kies uw Pizza.</h1>
<form id="Pi">
<input type="checkbox" name="P1" id="g"> €6,00 -Margherita (Kaas en tomaten)
<br/>
<input type="checkbox" name="P2" id="h"> €7,20 -Napolitana (tomaten, kaas, kappertjes, ansjovis)
<br/>
<input type="checkbox" name="P3" id="i"> €7,50 -Salami (kaas, tomaten en salami)
<br/>
<input type="checkbox" name="P4" id="j"> €7,50 -Prosciutto (tomaten, kaas, ham)
<br/>
<input type="checkbox" name="P5" id="k"> €7,00 -Funghi (tomaten, kaas, champions)
<br/>
<input type="checkbox" name="P6" id="l"> €8,00 -Tonno (tomaten, kaas, tonijn, ui)
<br/>
<input type="button" id="knop" value="button" />
</form>
</div>
<div class="container" id="Boxx">
<div id="ingrediënten">
<div>
<h1>Kies extra ingredienten</h1>
</div>
<div id="ingp1"></div>
<div id="ingp2"></div>
<div id="ingp3"></div>
<div id="ingp4"></div>
<div id="ingp5"></div>
<div id="ingp6"></div>
<input type="button" id="knop2" value="Totaal" />
</div>
</div>
So the problem I have is that when I look if one or more of P1 to P6 is check then it shows all 6 div with id ingp1 to ingp6.
I want it to show ingp1 when P1 is checked, and ingp3 when P3 is checked. You get it.
How do I do this (small thing I am only allowed to use javascript and jquery).
First of all add a common class names for the elements in the form and the div's in the container as I have given test1,test2 etc.
$('document').ready(function() {
var test
$("#Pi input[ type = 'checkbox']").click(function() {
var test = this.className
if ( this.checked == true )
{
$('#ingredienten .'+test).show()
console.log($('#ingrediënten .'+test))
}
else
{
$('#ingrediënten .'+test).hide()
}
})
})
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js" integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=" crossorigin="anonymous"></script>
</head>
<body>
<div class="Pizzas container" id="checkbox_pizza">
<h1>Kies uw Pizza.</h1>
<form id="Pi">
<input type="checkbox" class = "test1" name="P1" id="g"> €6,00 -Margherita (Kaas en tomaten)
<br/>
<input type="checkbox" class = "test2" name="P2" id="h"> €7,20 -Napolitana (tomaten, kaas, kappertjes, ansjovis)
<br/>
<input type="checkbox" class = "test3" name="P3" id="i"> €7,50 -Salami (kaas, tomaten en salami)
<br/>
<input type="checkbox" class = "test4" name="P4" id="j"> €7,50 -Prosciutto (tomaten, kaas, ham)
<br/>
<input type="checkbox" class = "test5" name="P5" id="k"> €7,00 -Funghi (tomaten, kaas, champions)
<br/>
<input type="checkbox" class = "test6" name="P6" id="l"> €8,00 -Tonno (tomaten, kaas, tonijn, ui)
<br/>
<input type="button" id="knop" value="button" />
</form>
</div>
<div class="container" id="Boxx">
<div id="ingredienten">
<div>
<h1>Kies extra ingredienten</h1></div>
<div id="ingp1" class = "test1">
</div>
<div id="ingp2" class = "test2">
</div>
<div id="ingp3" class = "test3">
</div>
<div id="ingp4" class = "test4">
</div>
<div id="ingp5" class = "test5">
</div>
<div id="ingp6" class = "test6">
</div>
<input type="button" id="knop2" value="Totaal" />
</div>
</div>
</body>
<html>
Then take the class name of the clicked check-box and search the div with the class name of this check-box and show or hide the div depending on its checked property.
try this
for (var q = 1; q <= 6; q++)
{
if ( $( 'input[ name = "P' + q + '"]').is(":checked") )
{
$( 'div#ingp' + q ).show();
}
}
$("#button").click(function () {
$('input[name^=P]').each(function () {
var idx = this.name.replace('P', '');
$('div#ingp' + idx).toggle(this.checked);
});
});
In words
for each <input> whose name starts with 'P',
find the associated <div> with the proper ID
toggle its visibility based on whether the <input> is checked or not
#Ttech thanks for clarifying the SO to me. Here's my solution. I slightly changed the markup in the part concerning the ids of the extra ingredients section (the divs).
Please, check my working example and see if this is what you need.
$('#ingrediënten div').hide();
$('#knop').on('click', function() {
$('#ingrediënten div').hide();
var $checkedOptions = $('#Pi input[type=checkbox]').filter(':checked'),
$extraIngredients = $('#ingrediënten div');
$checkedOptions.each(function() {
var id = $(this).attr('name');
$extraIngredients.filter('[id=' + id + ']').show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="Pizzas container" id="checkbox_pizza">
<h1>Kies uw Pizza.</h1>
<form id="Pi">
<input type="checkbox" name="P1" id="g"> €6,00 -Margherita (Kaas en tomaten)
<br/>
<input type="checkbox" name="P2" id="h"> €7,20 -Napolitana (tomaten, kaas, kappertjes, ansjovis)
<br/>
<input type="checkbox" name="P3" id="i"> €7,50 -Salami (kaas, tomaten en salami)
<br/>
<input type="checkbox" name="P4" id="j"> €7,50 -Prosciutto (tomaten, kaas, ham)
<br/>
<input type="checkbox" name="P5" id="k"> €7,00 -Funghi (tomaten, kaas, champions)
<br/>
<input type="checkbox" name="P6" id="l"> €8,00 -Tonno (tomaten, kaas, tonijn, ui)
<br/>
<input type="button" id="knop" value="button" />
</form>
</div>
<div class="container" id="Boxx">
<div id="ingrediënten">
<div>
<h1>Kies extra ingredienten</h1>
</div>
<div id="P1">
Extra ingredient 1
</div>
<div id="P2">
Extra ingredient 2
</div>
<div id="P3">
Extra ingredient 3
</div>
<div id="P4">
Extra ingredient 4
</div>
<div id="P5">
Extra ingredient 5
</div>
<div id="P6">
Extra ingredient 6
</div>
<br>
<input type="button" id="knop2" value="Totaal" />
</div>
</div>

How to loop through the textboxes in JavaScript

I am trying to make an a form with textboxes. when I check the checkboxes a text box will appear and I can input values. when I click the submit button it should give an alert showing only the values which I have entered.
How to use a loop for this content?
<!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">
<title>Bootstrap - Prebuilt Layout</title>
<!-- Bootstrap -->
<link href="../../../css/bootstrap.css" rel="stylesheet">
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script src="../../../js/bootstrap.min.js"></script>
<script src="../../../js/jquery-1.11.2.min.js"></script>
<script src="../../../js/collapse.js"></script>
</head>
<body>
<div class="container">
<script>
var i;
var j;
</script>
<button type="button" class="btn btn-info" data-toggle="collapse"
data-target="#demo1">Item 1</button>
<div id="demo1" class="collapse ">
<div class="checkbox">
<label data-toggle="collapse" data-target="#collapseOne">
<input type="checkbox" id="check1"/> Option 1
</label>
</div>
<div id="collapseOne" class="panel-collapse collapse">
<div class="panel-body">
<div class="driving-license-kind">
<div style="padding:16px">
No. of people : <input type="text" id="textbox1"></input>
</div>
</div>
</div>
</div>
<div class="checkbox" j="2">
<label data-toggle="collapse" data-target="#collapseTwo">
<input type="checkbox" id="check2"/> Option 2
</label>
</div>
<div id="collapseTwo" class="panel-collapse collapse">
<div class="panel-body">
<div class="driving-license-kind">
<div style="padding:16px">
No. of people : <input type="text" id="textbox2"></input>
</div>
</div>
</div>
</div>
</div>
<button type="button" class="btn btn-info" data-toggle="collapse"
data-target="#demo2" i="2">Item 2</button>
<div id="demo2" class="collapse in">
<div class="checkbox" j="1">
<label data-toggle="collapse" data-target="#collapseThree">
<input type="checkbox" id="check3"/> Option 1
</label>
</div>
<div id="collapseThree" class="panel-collapse collapse">
<div class="panel-body">
<div class="driving-license-kind">
<div style="padding:16px">
No. of people : <input type="text" id="textbox3" ></input>
</div>
</div>
</div>
</div>
<div class="checkbox" j="2">
<label data-toggle="collapse" data-target="#collapseFour">
<input type="checkbox" id="check4"/> Option 2
</label>
</div>
<div id="collapseFour" class="panel-collapse collapse">
<div class="panel-body">
<div class="driving-license-kind">
<div style="padding:16px">
No. of people : <input type="text" id="textbox4"></input>
</div>
</div>
</div>
</div>
</div>
</div>
<input type="button" value="submit" onclick="myFunction();"/>
<script>
function myFunction() {
for(
if (document.getElementById("check1").checked){
var x = document.getElementById("textbox1");
var content= "Item 1 Option 1: "+ x.value;
document.write(content);
}
if (document.getElementById("check2").checked){
var y = document.getElementById("textbox2");
var content= "Item 1 Option 2: "+ y.value;
document.write(content);
}
if (document.getElementById("check3").checked){
var z = document.getElementById("textbox3");
var content= "Item 2 Option 1: "+ z.value;
document.write(content);
}
if (document.getElementById("check4").checked){
var w = document.getElementById("textbox4");
var content= "Item 2 Option 2 : "+ w.value;
document.write(content);
}
}
</script>
</body>
</html>
If your html looks like this, and you do not have other <input type="text"> tags on your form:
<input type="checkbox" id="check1" value="text1" onclick='showHide(this);' /><input type="text" id="text1" style="display:none"/> <br>
<input type="checkbox" id="check2" value="text2" onclick='showHide(this);'/><input type="text" id="text2" style="display:none"/> <br>
<input type="checkbox" id="check3" value="text3" onclick='showHide(this);'/><input type="text" id="text3" style="display:none"/> <br>
<input type="checkbox" id="check4" value="text4" onclick='showHide(this);'/><input type="text" id="text4" style="display:none"/> <br>
<input type="button" onclick='alertChecked()' value='alert checked'/>
Then you can use javascript solution:
function showHide(source){
var textBox = document.getElementById(source.value);
if (isHidden(textBox)){
textBox.style.display = 'inline';
}
else{
textBox.style.display = 'none';
}
}
function alertChecked(){
var text = '';
var inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
if (inputs[index].type == 'text' && isHidden(inputs[index]) === false){
text += inputs[index].value;
}
}
alert(text);
}
function isHidden(el) {
return (el.offsetParent === null)
}
Demo fiddle: http://jsfiddle.net/ggcse3zz/1/
Or jQuery solution:
function showHide(source){
$('#'+source.value).toggle();
}
function alertChecked(){
var text = '';
$('input[type=text]:visible').each(function(){
text += $(this).val();
});
alert(text);
}
Demo fiddle: http://jsfiddle.net/ggcse3zz/
EDIT based on added HTML in question
Based on your html, you can use array of ids to find all yours input tags and loop them:
function myFunction(){
var text = '';
var textboxes = ["textbox1", "textbox2", "textbox3", "textbox4"];
for (index = 0; index < textboxes.length; ++index) {
var input = document.getElementById(textboxes[index]);
if (isHidden(input) === false){
text += input.value;
}
}
alert(text);
}
function isHidden(el) {
return (el.offsetParent === null)
}
Note that this javascript relies on the visibility of the input tag, not if checkbox is checked or not.
Demo fiddle: http://jsfiddle.net/usvLe3r1/
You should enhance myFunction() method:
function myFunction() {
var $checkboxes = $("input[id*='check']");
for (i = 0; i <= $checkboxes.length; i++) {
if ($checkboxes.get(i).checked) {
var orderNo = i + 1;
var content= "Item " + orderNo + " Option " + orderNo + ": "+ $("#textbox"+ orderNo).val();
alert(content);
}
}
}
I hope it's help.

Categories