In my HTML I have a form, where a user can select the checkbox "other" and a textbox appears. Otherwise the textbox is hidden. Below you can find my code. But if the user selects "other", types in his text und submits the form, the textbox is hidden again-although the checkbox maintain checked (saved in localStorage). I cannot find my mistake here.
Form:
<label class="form-check">
<input class="form-check-input" name="filetype" type="checkbox" id="other" value="" onclick="save()">
<span class="form-check-label"
<input placeholder="e.g. 'msg'" name="other" onsubmit="save();" class="form-control input-lg" type="text" id="otherValue" value="{{extension}}">
</span>
</label> <!-- form-check -->
Visible/Hidden
<!--"Other"-filter-->
<script type="text/javascript">
var otherCheckbox = document.querySelector('input[id="other"]');
var otherText = document.querySelector('input[id="otherValue"]');
otherText.style.visibility = 'hidden';
otherCheckbox.onchange = function(){
if(otherCheckbox.checked) {
otherText.style.visibility = 'visible';
otherCheckbox.value = otherText.value;
save();
} else {
otherText.style.visibility = 'hidden';
}
};
</script>
Tried to solve this Problem by saving the info in the sessionStorage but it still does not work.
<!--Save Checkbox-State-->
<script type="text/javascript">
const checkboxen = [...document.querySelectorAll("[type=checkbox]")].map(inp => inp.id); //list of all checkbox-IDs
function save(){
for (var i = 0 ; i< checkboxen.length; i++){
var id = checkboxen[i];
var checkbox = document.getElementById(id);
sessionStorage.setItem(id,checkbox.checked);
}
var other = document.getElementById('otherValue');
sessionStorage.setItem('otherValue',other.style.visibility);
}
function load(){
for (var i = 0 ; i< checkboxen.length; i++){
var id = checkboxen[i];
var checked =JSON.parse(sessionStorage.getItem(id));
document.getElementById(id).checked = checked;
}
var other = JSON.parse(sessionStorage.getItem('otherValue'));
document.getElementById('otherValue').style.visibility = other;
}
function deleteCheckbox(){
sessionStorage.clear();
}
</script>
Thanks for any help <3
with prop jquery:
<script>
$(function(){
var other = localStorage.input === 'true'? true: false;
$('input').prop('checked', other);
});
$('input').on('change', function() {
localStorage.input = $(this).is(':checked');
console.log($(this).is(':checked'));
});
</script>
this is my solution:
<script type="text/javascript">
var other = document.getElementById('other');
var otherText =document.querySelector('input[id="otherValue"]');
$(document).ready(function(){
if (other.checked){
otherText.style.visibility = 'visible';
otherText.value = "{{extension}}";
other.value = "{{extension}}";
} else {
otherText.style.visibility = 'hidden';
otherText.value = "";
}
});
Related
I'm trying to code a small application that lets you dynamically add text strings in an unordered list, but the problem is the strings I pass as input do not show up after clicking the "Invia/Send" button. I have tried with a few solutions from other questions, but none of them worked. Any ideas?
<html>
<head>
<title>Promemoria esercizi</title>
</head>
<body>
<ul id="paragraphList">
</ul>
<form id="paragraphForm">
<br></br>
<textarea id="insertParagraph" rows="5" cols="100"></textarea>
<label>Inserisci il paragrafo:
<input type="radio" id="insertType" name="InsertType" value="last">In fondo
<input type="radio" id="insertType" name="InsertType" value="before">Dietro il paragrafo
<select id="beforeParagraph"></select><br></br>
</label>
<button id="add" onclick="addParagraph(paragraphArray)">Inserisci</button><br></br>
</form>
<script>
var paragraphArray = [];
document.getElementById("paragraphList").innerHTML = paragraphArray;
function addParagraph(paragraphArray){
var text = document.getElementById("insertParagraph").value;
var radio = document.getElementById("insertType");
var selectedInsertType = "";
var ul = document.getElementById("paragraphList");
var sel = document.getElementById("beforeParagraph");
var selectedBeforeParagraph = sel.options[sel.selectedIndex].value;
for(i = 0; i < radio.length; i++){
if(radio[i].checked){
selectedInsertType = radio[i].value;
}
}
if(selectedInsertType = "last"){
paragraphArray.push(text);
}else if(selectedInsertType = "before"){
paragraphArray.splice((selectedBeforeParagraph-1), 0, text);
}
var newChoice = document.createElement("option");
newChoice.value = paragraphArray.length.toString();
newChoice.text = paragraphArray.length.toString();
for(i = 0; i < paragraphArray.length; i++){
var li = document.createElement("li");
li.innerHTML = paragraphArray[i];
}
document.getElementById("paragraphList").innerHTML = paragraphArray;
}
</script>
</body>
</html>
There were a few issues:
A common problem people run into with the button tag is by default, it has a type of 'submit' which will submit the form. There are a few ways to disable this, my preferred method is to set the type as button.
Another issue is you don't have any content in the select box, which was causing an error trying to get the value of a select box with no options that can be selected.
I updated your radios, to use querySelectorAll and look for :checked that way you don't need to create an if statement.
I also removed the paragraphArray from addParagraph() since it is a global variable.
<html>
<head>
<title>Promemoria esercizi</title>
</head>
<body>
<ul id="paragraphList">
</ul>
<form id="paragraphForm">
<br></br>
<textarea id="insertParagraph" rows="5" cols="100"></textarea>
<label>Inserisci il paragrafo:
<input type="radio" id="insertType" name="InsertType" value="last">In fondo
<input type="radio" id="insertType" name="InsertType" value="before">Dietro il paragrafo
<select id="beforeParagraph"></select><br></br>
</label>
<button type="button" id="add" onclick="addParagraph()">Inserisci</button><br></br>
</form>
<script>
var paragraphArray = [];
document.getElementById("paragraphList").innerHTML = paragraphArray;
function addParagraph(){
var text = document.getElementById("insertParagraph").value;
var radio = document.querySelectorAll("#insertType:checked");
var selectedInsertType = "";
var ul = document.getElementById("paragraphList");
var sel = document.querySelector("#beforeParagraph");
var selectedBeforeParagraph = (sel.selectedIndex > -1) ? sel.options[sel.selectedIndex].value : "";
for(i = 0; i < radio.length; i++){
selectedInsertType = radio[i].value;
}
if(selectedInsertType = "last"){
paragraphArray.push(text);
}else if(selectedInsertType = "before"){
paragraphArray.splice((selectedBeforeParagraph-1), 0, text);
}
var newChoice = document.createElement("option");
newChoice.value = paragraphArray.length.toString();
newChoice.text = paragraphArray.length.toString();
for(i = 0; i < paragraphArray.length; i++){
var li = document.createElement("li");
li.innerHTML = paragraphArray[i];
}
document.getElementById("paragraphList").innerHTML = paragraphArray;
}
</script>
</body>
</html>
var radios = document.getElementsByTagName('input');
for (i = 0; i < radios.length; i++) {
radios[i].onclick = function () {
if (this.checked) {
this.checked = false;
}
}
}
<div id = "container">
<input type = "radio" name = "x"> A
<br>
<input type = "radio" name = "x"> B
</div>
what i want is to check one of the radios and if i pressed the checked radio again to uncheck it but it does not check in first place too
how to uncheck a checked radio after it was checked and how to even tell that it is checked or in empty state
I will suggest that you use attribute to control the checked status.
var x = document.getElementsByName('x');
x.forEach(function(e) {
e.addEventListener('click', function(ev) {
// set checked by data-checked attribute
if (e.getAttribute('data-checked') == 'true') {
e.checked = false;
e.setAttribute('data-checked', 'false');
} else {
e.checked = true;
e.setAttribute('data-checked', 'true');
}
// update attribute of all radios
x.forEach(function(e2) {
e2.setAttribute('data-checked', e2.checked);
});
});
});
<input type="radio" name="x" data-checked="false"> A<br>
<input type="radio" name="x" data-checked="false"> B<br>
<input type="radio" name="x" data-checked="false"> C<br>
Using your current JavaScript code, the moment you click it, it will be checked first before reading the JavaScript code, thus it will appear to be unchecked always. With my suggestions (it can't be helped sorry) use something like this:
var radios = document.getElementsByTagName('input');
for (i = 0; i < radios.length; i++) {
radios[i].onmousedown = function () {
if (this.checked) {
this.checked = false;
this.onchange = function () {
this.checked = false;
}
}
else {
this.checked = true;
this.onchange = function () {
this.checked = true;
}
}
}
}
<div id = "container">
<input type = "radio" name = "x"> A
<br>
<input type = "radio" name = "x"> B
</div>
Since I can't question you why you can't use checkbox instead, I had to do this. It works for me anyway
Use the following code. This is the whole code, try using it:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body >
<div id = "container">
<input type = "radio" name = "x"> A
<br>
<input type = "radio" name = "x"> B
</div>
</body>
<script type="text/javascript">
var radios = document.getElementsByTagName('input');
for (i = 0; i < radios.length; i++) {
radios[i].onclick = function () {
console.log("==>" , this.checked);
if (this.checked == false) {
this.checked = true;
}else{
this.checked = true;
}
}
}
</script>
</html>
I'm trying to get the button to be enabled only when all three condition are met which are at least one checkbox is selected in the 1st checkbox list and 2nd checkbox selected and option list selected.
For the 1st condition i was thinking as an alternative would javascript be able to check on strlen of the textbox ?
Somehow the pure javascript below is not working and would it be possible if selection by the user goes in reverse ?
Pure javascript:
<script type = "text/javascript">
document.addEventListener("DOMContentLoaded", function() {
document.getElementById('termsChkbx').addEventListener("change", function(){
this.parentNode.style.color = this.checked ? "black" : "red";
}, false);
});
function change(obj) {
var selectBox = obj;
var selected = selectBox.options[selectBox.selectedIndex].value;
var retCustDetails = document.getElementById("retCustDetails");
var tradeCustDetails = document.getElementById("tradeCustDetails");
if(selected === 'ret'){
retCustDetails.style.display = "block";
tradeCustDetails.style.display = "none";
}
else if (selected === 'trd') {
retCustDetails.style.display = "none";
tradeCustDetails.style.display = "block";
}
else if (selected === '') {
retCustDetails.style.display = "none";
tradeCustDetails.style.display = "none";
}
}
function isChecked() {
var sum = 0; //store a running sum
//find all price elements: class "CDPrice" within element of class "item"
[].forEach.call(document.querySelectorAll(".item .CDPrice"), function(item) {
//get the corresponding checkbox
var chosen = item.parentElement.querySelector('[type="checkbox"]');
//if checked, add to the running sum
if (chosen.checked) {
var value = parseFloat(item.innerHTML) || 0; //if parseFloat() returns none, default value to zero
sum += value;
}
});
//update the total
var total = document.getElementById("total");
total.value = sum.toFixed(2);
}
function Checked() {
var checkedRadioButtons = document.querySelector('[name="deliveryType"]:checked');
document.getElementById("total").value = checkedRadioButtons.getAttribute("title");
}
//conditions for submit button to be enable
//var firstCondition = document.querySelectorAll('name=CDPrice');
//var termsCheckbox = document.getElementById('termsChkbx');
var show = document.getElementById('show');
var button = document.getElementById('sub1');
var conditions = {
// cond1: false,
// cond2: false,
cond3: false
};
//function setCondition1(e) {
// conditions.cond1 = e.target.checked;
// enableButton(conditions);
//}
//function setCondition2(e) {
// conditions.cond2 = e.target.checked;
// enableButton(conditions);
//}
function setCondition3(e) {
conditions.cond3 = e.target.value && e.target.value.length > 0;
enableButton(conditions);
}
function enableButton(options) {
if (options.cond3) {
button.removeAttribute('disabled');
} else {
button.setAttribute('disabled', true);
}
}
//for(i=0 ; i< firstCondition.length ; i++){
// firstCondition[i].addEventListener("click", setCondition1, false);
//}
//termsCheckbox.addEventListener('change', setCondition2, false);
show.addEventListener('change', setCondition3, false);
</script>
1st condition -> Checkbox list or textbox:
<?php
include_once('database_conn.php');
$sqlCDs = 'SELECT CDID, CDTitle, CDYear, catDesc, CDPrice FROM nmc_cd b inner join nmc_category c on b.catID = c.catID WHERE 1 order by CDTitle';
$rsCDs = mysqli_query($conn, $sqlCDs);
while ($CD = mysqli_fetch_assoc($rsCDs)) {
echo "\t<div class='item'>
<span class='CDTitle'>{$CD['CDTitle']}</span>
<span class='CDYear'>{$CD['CDYear']}</span>
<span class='catDesc'>{$CD['catDesc']}</span>
<span class='CDPrice'>{$CD['CDPrice']}</span>
<span class='chosen'><input type='checkbox' name='CD[]' value='{$CD['CDID']}' title='{$CD['CDPrice']}'onchange='isChecked();'/></span>
</div>\n";
}
?>
<section id="checkCost">
<h2>Total cost</h2>
Total <input type="text" name="total" id="total" size="10" readonly="readonly" />
</section>
2nd condition -> 2nd checkbox:
<p style="color: red; font-weight: bold;">I have read and agree to the terms and conditions
<input type="checkbox" id="termsChkbx" onchange="isChecked(this,'sub1')"/></p>
3rd condition -> Option List:
<section id="placeOrder">
<h2>Place order</h2>
Your details
Customer Type: <select id="show" name="customerType" onchange="change(this)">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
Submit Button:
<p><input type="submit" name="submit" value="Order now!" id="sub1" disabled="disabled"/></p>
You can attach event listeners on each input and listen for changes.
var firstCondition = document.querySelectorAll('input[name="testName"]');
var termsCheckbox = document.getElementById('termsChkbx');
var show = document.getElementById('show');
var button = document.getElementById('sub1');
Object to hold all the conditions
var conditions = {
cond1: false,
cond2: false,
cond3: false
}
Declared functions to use with addEventListener
function setCondition1(e) {
conditions.cond1 = e.target.checked;
enableButton(conditions);
}
function setCondition2(e) {
conditions.cond2 = e.target.checked;
enableButton(conditions);
}
function setCondition3(e) {
conditions.cond3 = e.target.value && e.target.value.length > 0;
enableButton(conditions);
}
Enable button
function enableButton(options) {
if (options.cond1 && options.cond2 && options.cond3) {
button.removeAttribute('disabled');
} else {
button.setAttribute('disabled', true);
}
}
Add event listeners
for(i=0 ; i< firstCondition.length ; i++){
firstCondition[i].addEventListener("click", setCondition1, false);
}
termsCheckbox.addEventListener('change', setCondition2, false);
show.addEventListener('change', setCondition3, false);
example: http://jsfiddle.net/qjo9rqgc/
Here's what i'm trying to achieve: I want to create a HTML page with a form, when you submit the form it goes to 1 of 4 locations. There is a default hidden main option thats auto-selected on page load and 2 sub-options that are optional.
Oh, and it calculates the amounts on selection!
Here's my code so far:
<html>
<head></head>
<body>
<form onSubmit="submitForm();" id="myForm" type="get">
<input id="myCheckbox1" name="myCheckbox1" type="checkbox" value="20" onClick="calcNow();" />Default option<br/>
<input id="myCheckbox2" name="myCheckbox2" type="checkbox" value="30" onClick="calcNow();" />Add-on option 1<br/>
<input id="myCheckbox2" name="myCheckbox2" type="checkbox" value="40" onClick="calcNow();" />Add-on option 2<br/>
<input id="myTotal" name="myTotal" type="text" value="" disabled="disabled" /><br/>
<input type="button" id="myButton" onClick="submitForm();" value="Continue" />
</form>
<script type="text/javascript">
var pages = [[["http://mysite.com/page1.html"],["http://mysite.com/page2.html"],["http://mysite.com/page3.html","http://mysite.com/page4.html"]]];
function calcNow()
{
var cb = document.getElementById("myCheckbox1");
var cb = document.getElementById("myCheckbox2");
var cost1 = cb.checked ? parseInt(cb.value) : 0;
var cost2 = cb.checked ? parseInt(cb.value) : 0;
var costTotal = cost1 + cost2;
document.getElementById("myTotal").value = costTotal;
var op1 = cb.checked ? 1 : 0;
if (op1 != undefined)
{
return pages[op1];
}
return undefined;
}
function submitForm()
{
var page = calcNow();
if (page != undefined)
{
alert(page);
// ---- To navigate ----
//location.href = page;
// ---- To alter post ----
//var form = document.getElementById("myForm");
//form.action = page;
//form.submit();
}
else
{
alert("Please answer all questions.");
}
}
function getRadioValue(name)
{
var controls = document.getElementsByName(name);
for (var i = 0; i < controls.length; i++) {
if (controls[i].checked) {
return parseInt(controls[i].value);
}
}
return 0;
}
function getRadioData(name, attribute)
{
var controls = document.getElementsByName(name);
for (var i = 0; i < controls.length; i++) {
if (controls[i].checked) {
return parseInt(controls[i].dataset[attribute]);
}
}
return undefined;
}
</script>
</body>
</html>
Try this
EDIT:
function submitForm()
{
//The code goes inside here, you have to decide where to redirect from if or the else
window.location.assign("http://www.w3schools.com/");
var page = calcNow();
if (page != undefined)
{
alert(page);
}
else
{
alert("Please answer all questions.");
}
}
I have an issue to create dynamic fields with string count using JavaScript or jQuery.
Briefing
I want to create dynamic fields with the help of sting count, for example when I write some text on player textfield like this p1,p2,p3 they create three file fields on dynamicDiv or when I remove some text on player textfield like this p1,p2 in same time they create only two file fields that's all.
The whole scenario depend on keyup event
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function commasperatedCount(){
var cs_count = $('#player').val();
var fields = cs_count.split(/,/);
var fieldsCount = fields.length;
for(var i=1;i<=fieldsCount;i++){
var element = document.createElement("input");
element.setAttribute("type", 'file');
element.setAttribute("value", '');
element.setAttribute("name", 'file_'+i);
var foo = document.getElementById("dynamicDiv");
foo.appendChild(element);
}
}
</script>
<form>
<label>CountPlayerData</label>
<input type="text" name="player" id="player" onkeyup="return commasperatedCount();" autocomplete="off" />
<div id="dynamicDiv"></div>
<input type="submit" />
</form>
var seed = false,
c = 0,
deleted = false;
$('#player').on('keyup', function(e) {
var val = this.value;
if ($.trim(this.value)) {
if (e.which == 188) {
seed = false;
}
if (e.which == 8 || e.which == 46) {
var commaCount = val.split(/,/g).length - 1;
if (commaCount < c - 1) {
deleted = true;
}
}
commasperatedCount();
} else {
c = 0;
deleted = false;
seed = false;
$('#dynamicDiv').empty();
}
});
function commasperatedCount() {
if (deleted) {
$('#dynamicDiv input:last').remove();
deleted = false;
c--;
return false;
}
if (!seed) {
c++;
var fields = '<input value="" type="file" name="file_' + c + '">';
$('#dynamicDiv').append(fields);
seed = true;
}
}
DEMO
<script>
function create(playerList) {
try {
var player = playerList.split(/,/);
} catch(err) {
//
return false;
}
var str = "";
for(var i=0; i<player.length; i++) {
str += '<input type="file" id="player-' + i + '" name="players[]" />';
//you wont need id unless you are thinking of javascript validations here
}
if(playerList=="") {str="";} // just in case text field is empty ...
document.getElementById("dynamicDiv").innerHTML = str;
}
</script>
<input id="playerList" onKeyUp="create(this.value);" /><!-- change event can also be used here -->
<form>
<div id="dynamicDiv"></div>
</form>