Button enabled from 3 condition - javascript

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/

Related

Input value is not changed on Javascript

I make shopping Cart now with vanilla javascript, html, css.
This program is when consumer click selection tag, add new tag and change count.
To Add new Tag is already working. Change count is not work. When I clicked, selectA, selectB, selectC is changed but not working on input tag.
var selectA = 0;
var selectB = 0;
var selectC = 0;
function handleOnChange(e) {
// 선택된 데이터 가져오기
let value = e.value;
let name = e.options[e.selectedIndex].text;
let itemList = document.getElementById("addItem");
var Item = document.createElement('div');
var itemName = document.createElement('div');
var itemSumA = document.createElement('input');
var itemSumB = document.createElement('input');
var itemSumC = document.createElement('input');
itemName.innerHTML = name;
if (value === "A") {
if (selectA === 0) {
Item.appendChild(itemName);
Item.appendChild(itemSumA);
itemList.appendChild(Item);
}
itemSumA.value = selectA;
} else if (value === "B") {
console.log(selectB);
if (selectB === 0) {
Item.appendChild(itemName);
Item.appendChild(itemSumB);
itemList.appendChild(Item);
}
itemSumB.value = ++selectB;
} else {
if (selectC === 0) {
Item.appendChild(itemName);
Item.appendChild(itemSumC);
itemList.appendChild(Item);
}
itemSumC.value = ++selectC;
}
document.getElementById("Sum").innerHTML = selectA * 39800 + selectB * 49800 + selectC * 59800;
}
<li class="checked">
<button class="accordion">주문 정보</button>
<div class="panel">
<p>상품 선택</p>
<select name="tent" id="tent" onchange="handleOnChange(this)">
<option value="A">A. 스피드 원터치 팝업텐트(3~4인용)</option>
<option value="B">B. 5초 원터치 텐트(3인용) (+10,000)</option>
<option value="C">C. 5초 원터치 텐트(5인용) (+20,000)</option>
</select>
<div id="addItem"></div>
</div>
</li>
I want to know why.

html javascript (game) how to retrieve value of button point is added when a button is clicked

i am creating a game. the game should work this way: when user click on the button with target option that was chosen previously from the dropdown list, score will +2, else -1.
however, the code i have now is not working, the score is not adding, its always 0. i am guessing it is because i didn't retrieve the value of the button correctly, hence, the value of the button chosen and target option value never match. how can i solve this issue??
background information: the 3 options will refresh every 1/2/3 seconds depending on the difficulty level chosen. hence, the option will always be different, there will also be situation where none of the 3 options is the target option. user can choose to wait for 1/2/3 seconds OR click on any of the option and receive a -1 point.
here is my code for the part where the score is calculated
document.getElementById("TO1").addEventListener("click", clickScore);
document.getElementById("TO2").addEventListener("click", clickScore);
document.getElementById("TO3").addEventListener("click", clickScore);
//score system
function clickScore() {
//when one option is clicked , all 3 options will change value
var option1 = document.getElementById("TO1").value;
var option2 = document.getElementById("TO2").value;
var option3 = document.getElementById("TO3").value;
var btn1 = document.getElementById("TO1");
var btn2 = document.getElementById("TO2");
var btn3 = document.getElementById("TO3");
if (btn1.clicked && option1.hasAttribute(targetValue) == true ){
score = parseInt(document.getElementById("score").innerHTML);
score += 2;
//random10Opt;
}
else if (btn1.clicked && option1.hasAttribute(targetValue) == false)
{
score -=1;
//random10Opt;
}
if (btn2.clicked && option2.hasAttribute(targetValue) == true ){
score = parseInt(document.getElementById("score").innerHTML);
score += 2;
//random10Opt;
}
else if (btn2.clicked && option2.hasAttribute(targetValue) == false)
{
score -= 1;
//random10Opt;
}
if (btn3.clicked && option3.hasAttribute(targetValue) == true ){
score = parseInt(document.getElementById("score").innerHTML);
score += 2;
//random10Opt;
} else if (btn3.clicked && option3.hasAttribute(targetValue) == false)
{
score -= 1;
//random10Opt;
}
document.getElementById("score").innerHTML = score;
}; //end of click
here is the entire code i have
<!DOCTYPE html>
<html>
<body>
<div>
<form name="start" id="start">
<table id="T">
<tr id="Ttitle"> <!-- Header -->
<th colspan="3"><h2>Assignment 3 Part 2: Game</h2></th>
</tr>
<tr id="Tplayer"> <!-- ROW 1 PLAYER NAME-->
<th>Player Name</th>
<td><!-- text box for Unique name -->
<input type="text" id="name" name="required name" placeholder="Enter your Name"><br>
<span style="color:red;" id="nameError"></span>
</td>
<td id="TS" rowspan="3"> <!-- TIMER AND SCORE -->
<h3>Time: </h3>
<div class="timeScore" ><span id="seconds">00</span>:<span id="tens">00</span> second(s)</div>
<h3>Score: </h3>
<div class="timeScore" ><span id="score">0</span></div>
</td> <!-- Time and Score -->
</tr>
<tr id="Ttarget"> <!-- ROW 2 TARGET OPTION-->
<th>The Target Option: </th>
<td> <!-- list box with all option -->
<select name="target_Opt" id="target_Opt">
<option value="">Choose your Target</option>
</select>
<span style="color:red;" id="TargetError"></span>
</td>
</tr>
<tr id="Tdifficulty"> <!-- ROW 3 DIFFICULTY LEVEL-->
<th>The Difficulty Level: </th>
<td id="radio"> <!-- Radio button Low, Med, High -->
<input type="radio" id="Low" name="difficulty" value="low" checked>
Low
<input type="radio" id="Medium" name="difficulty" value="med">
Medium
<input type="radio" id="High" name="difficulty" value="high">
High
</td>
</tr>
<tr id="Tbutton"> <!-- ROW 4 START STOP Button-->
<td colspan="3">
<input type="button" id="startBtn"
value="Start" >
<input type="button" id="stopBtn" value="Stop" >
</td>
</tr>
<tr id="Toptions"> <!-- ROW 5 CLICK Options -->
<td class="Opt">
<input type="button" class="gameOpt" id="TO1" value="Option 1" >
</td>
<td class="Opt">
<input type="button" class="gameOpt" id="TO2" value="Option 2" >
</td>
<td class="Opt">
<input type="button" class="gameOpt" id="TO3" value="Option 3" >
</td>
</tr>
</table>
<div id="Tlist" >
<h4> Player Listing : </h4>
<ul id="myList">
</ul>
</div>
</form> <!--END OF FORM WHEN START IS CLICKED -->
</div>
</body>
<script>
var score = 0; //for score
var pn = []; //Array to contain PlayerName
var ten = []; //Array for 10 Random Options
var a = document.forms["start"]["name"].value; //get Player's name input
var targetValue = document.getElementById("target_Opt").value; //selected target
//ARRAY OF OPTIONS TO CHOOSE TARGET
var Opt123 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var OptABC = ["A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "O",
"P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z"];
//add options into dropdown list
function PrepopulateOpt() {
var selectTarget = document.getElementById("target_Opt");
var i = 1;
//add Opt123 into dropdown list
for (var target_Opt in Opt123) {
selectTarget.options[i++] = new Option(target_Opt);
}
//add OptABC into dropdown list
for (var i = 0; i < OptABC.length; i++) {
var opt = OptABC[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
selectTarget.appendChild(el);
}
}
PrepopulateOpt();
window.onload = function () {
var seconds = 00;
var tens = 00 ;
var appendTens = document.getElementById("tens");
var appendSeconds = document.getElementById("seconds");
var buttonStart = document.getElementById('startBtn');
var buttonStop = document.getElementById('stopBtn');
var Interval ;
var optionButton = document.getElementsByClassName('gameOpt'); //the options
//var changeOpt = document.getElementsByClassName("gameOpt").value; //option value
function ValidateEvent(){
var name = document.getElementById("name").value;
var target = document.getElementById("target_Opt").value;
//CHECK IF PLAYER NAME IS UNIQUE
if (name == null || name.trim() == "")
{
alert("Please enter your name");
return false;
} else if (pn.includes(name) == true){
alert("Please enter a unique name");
return false;
}
//CHECK IF TARGET IS SELECTED
if (target == "")
{
alert("Please select a target!") ;
return false;
}
else
{
document.getElementById("TargetError").value = "";
}
return true;
}
/* function removeDuplicates(data){
return data.filter((value, index) => data.indexOf(value) === index);
}
*/
function random10Opt(){
//targetValue = selected target value;
var target = document.getElementById("target_Opt").value;
//var target123 = parseInt(document.getElementById("target_Opt").value);
var index;
const newArr = [];
if (Opt123.includes(target) == true){
index = Opt123.indexOf(target);
Opt123.splice(index, 1);
return Opt123;
} else if (OptABC.includes(target) == true){
index = OptABC.indexOf(target);
OptABC.splice(index, 1);
return OptABC;
}
const a = Opt123.slice();
const b = OptABC.slice();
//select random 5 from digit add into newArr
for(let i= 5; i >= 0; i--){
let arr = a[Math.floor(Math.random()*a.length)];
let index = a.indexOf(arr);
a.splice(index, 1 );
newArr.push(arr);
}
for(let i= 5; i >= 0; i--){
let arr = b[Math.floor(Math.random()*b.length)];
let index = b.indexOf(arr);
b.splice(index, 1 );
newArr.push(arr);
}
newArr.push(target); //new array with randomized values : newArr
//enter random element into Option 1
var index1 = newArr[Math.floor(Math.random()*newArr.length)];
document.getElementById("TO1").value = index1;
var Arr2 = newArr.splice(index1, 1);
//enter random element into Option 2
var index2 = newArr[Math.floor(Math.random()*newArr.length)];
document.getElementById("TO2").value = index2;
var Arr3 = newArr.splice(index2, 1);
//enter random element into Option 3
var index3 = newArr[Math.floor(Math.random()*newArr.length)];
document.getElementById("TO3").value = index3;
console.log(newArr)
} //end of random10Opt
function difficultylvl() {
//TIME INTERVAL ACCORDING TO DIFFICULTY LEVEL
if (document.getElementById("Low").checked){
myVar = setInterval(random10Opt, 3000);
} else if (document.getElementById("Medium").checked){
myVar = setInterval(random10Opt, 2000);
} else {
myVar = setInterval(random10Opt, 1000);
}
} //end of difficulty level
//stop timeInterval for difficulty level
function stopInterval() {
clearInterval(myVar);
}
document.getElementById("TO1").addEventListener("click", clickScore);
document.getElementById("TO2").addEventListener("click", clickScore);
document.getElementById("TO3").addEventListener("click", clickScore);
//score system
function clickScore() {
//when one option is clicked , all 3 options will change value
var option1 = document.getElementById("TO1").value;
var option2 = document.getElementById("TO2").value;
var option3 = document.getElementById("TO3").value;
var btn1 = document.getElementById("TO1");
var btn2 = document.getElementById("TO2");
var btn3 = document.getElementById("TO3");
if (btn1.clicked && option1.hasAttribute(targetValue) == true ){
score = parseInt(document.getElementById("score").innerHTML);
score += 2;
//random10Opt;
}
else if (btn1.clicked && option1.hasAttribute(targetValue) == false)
{
score -=1;
//random10Opt;
}
if (btn2.clicked && option2.hasAttribute(targetValue) == true ){
score = parseInt(document.getElementById("score").innerHTML);
score += 2;
//random10Opt;
}
else if (btn2.clicked && option2.hasAttribute(targetValue) == false)
{
score -= 1;
//random10Opt;
}
if (btn3.clicked && option3.hasAttribute(targetValue) == true ){
score = parseInt(document.getElementById("score").innerHTML);
score += 2;
//random10Opt;
} else if (btn3.clicked && option3.hasAttribute(targetValue) == false)
{
score -= 1;
//random10Opt;
}
document.getElementById("score").innerHTML = score;
}; //end of click
buttonStart.onclick = function() {
if( ValidateEvent() == true) {
//checkform(); //check name and target
random10Opt(); //add random value into button
difficultylvl(); //setInterval
addName(); //add player name into list
if (seconds == 00 && tens == 00){
clearInterval(Interval);
Interval = setInterval(startTimer, 10);
} else {
clearInterval(Interval);
tens = "00";
seconds = "00";
appendTens.innerHTML = tens;
appendSeconds.innerHTML = seconds;
clearInterval(Interval);
Interval = setInterval(startTimer, 10);
}
}
};
buttonStop.onclick = function() {
clearInterval(Interval); //stop stopwatch
stopInterval(); //stop setInterval for options
//default value when the game stop
document.getElementById("TO1").value = "Option 1";
document.getElementById("TO2").value = "Option 2";
document.getElementById("TO3").value = "Option 3";
};
optionButton.onclick = function() {
clickScore(); //click the options for score
};
//stopwatch
function startTimer() {
tens++;
if(tens < 9){
appendTens.innerHTML = "0" + tens;
}
if (tens > 9){
appendTens.innerHTML = tens;
}
if (tens > 99) {
console.log("seconds");
seconds++;
appendSeconds.innerHTML = "0" + seconds;
tens = 0;
appendTens.innerHTML = "0" + 0;
}
if (seconds > 9){
appendSeconds.innerHTML = seconds;
}
}//end of startTimer()
function addName(){
//takes the value of player name
//pn is an empty array to contain to names
var newArray = document.getElementById("name").value;
pn.push(newArray);
var node = document.createElement("LI");
var textnode = document.createTextNode(newArray);
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
} //end of addName function
};//end on onload
</script>
</html>
you have registered the click-event twice.
just removed the onclick in the input
...
<input type="button" class="gameOpt" id="TO1" value="Option 1">
...
<input type="button" class="gameOpt" id="TO2" value="Option 2">
...
<input type="button" class="gameOpt" id="TO3" value="Option 3">
</td>
...
<script>
document.getElementById("TO1").addEventListener("click", clickScore);
document.getElementById("TO2").addEventListener("click", clickScore);
document.getElementById("TO3").addEventListener("click", clickScore);
Have a look at the snippet below, which I think illustrates what you're trying to accomplish.
Your buttons will be randomized at the outset. Then you can choose the "target value" from the drop-down, and clicking the button w/the value that matches your selected "target value" will add points, whereas clicking a button that doesn't match the target value will subtract points.
Note how much simpler it becomes to attach the click event handler in a way that allows you to read the event target's value.
var score = 0;
var newArr = [1, 2, 3, 4, 5, "A", "B", "C", "D", "E"];
let scoreOutput = document.getElementById("scoreUpdate");
const gameButtons = document.querySelectorAll(".gameOpt");
//this code just creates the select dropdown, which you don't need to do
var select = document.getElementById("targetValue");
for (var i = 0; i < newArr.length; i++) {
var opt = newArr[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
randomizeButtonValues();
//attach the click for each button
[...gameButtons].forEach((btn) => {
btn.addEventListener("click", (e) => {
let correctValue = document.getElementById("targetValue").value;
let clickedValue = e.target.value; // <-- capture value of clicked element
console.log(correctValue, clickedValue);
if(correctValue == clickedValue) {
score += 2;
} else {
score -= 1;
}
scoreOutput.innerHTML += `<br>New Score: ${score}`;
randomizeButtonValues();
});
});
function randomizeButtonValues() {
[...gameButtons].forEach((btn) => {
let rnd = Math.floor(Math.random() * newArr.length);
btn.value = newArr[rnd];
});
}
<select id="targetValue">
<option>Choose target value</option>
</select>
<input type="button" class="gameOpt" id="TO1" value="Option 1">
<input type="button" class="gameOpt" id="TO2" value="Option 2">
<input type="button" class="gameOpt" id="TO3" value="Option 3">
<br>
<div id="scoreUpdate"></div>

Maintain visibility of a form-textinput when checkbox is checked

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 = "";
}
});

uncheck checked radio button

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>

Angularjs devade tags when user put comma

I have a case in which I need to divide tags when the user put a comma separation, for the moment the user can only add tags one by one, what I want to do is allows user to enter more than one tag in the input separated by a comma:
This is what I have now :
this is what I want to do :
what I have so far :
<div class="form-group">
<label>Mes centres d'intérêt</label>
<div class="input-group" style="margin-bottom: 8px;">
<input id="tagInsert" type="text" name="newTag" ng-model="newTag" ng-model-options="{debounce: 100}" typeahead="tag for tag in getTags($viewValue)" class="form-control" typeahead-loading="loadingTags" ng-keydown="addInterestOnEvent($event)" ng-disabled="interestLimit" autocomplete="off">
<span class="input-group-btn"><span class="btn btn-primary" ng-click="addInterest()" analytics-on="click" ng-disabled="interestLimit" analytics-event="Ajout Interet" analytics-category="Profil">Ajouter</span></span>
</div>
<p class="form__field__error" ng-show="interestLimit">Vous avez atteint la limite de 10 centres d'intérêt.</p>
<ul class="tags">
<li class="tag" ng-repeat="name in user.interests track by $index">{{ name }} <i class="icon-close" ng-click="removeInterest($index)" analytics-on analytics-event="Supprimer Interet" analytics-category="Profil"></i></li>
</ul>
</div>
My controller :
$scope.getTags = function (name) {
return $http.get('/api/tags/' + name.replace('/', '')).then(function (result) {
var tags = result.data;
for (var i = tags.length; i--; ) {
var tagName = tags[i].name;
if ($scope.user.interests.indexOf(tagName) !== -1) tags.splice(i, 1);
else tags[i] = tagName;
}
return tags;
});
};
$scope.removeInterest = function (id) {
$scope.interestLimit = false;
$scope.user.interests.splice(id, 1);
}
$scope.addInterest = function () {
if ($scope.interestLimit) return;
var element = $document[0].getElementById('tagInsert'),
value = element.value;
if (value.length) {
element.value = '';
if ($scope.user.interests.indexOf(value) === -1) {
$scope.user.interests.push(value);
$scope.interestLimit = $scope.user.interests.length === 10;
}
}
};
$scope.addInterestOnEvent = function (event) {
if (event.which !== 13) return;
event.preventDefault();
$scope.addInterest();
};
$scope.remove = function () {
$scope.confirmModal = Modal.confirm.delete(function () {
User.remove(function () {
submit = true;
Auth.logout();
$location.path('/');
});
})('votre compte');
};
You should split value with comma and do for loop.
Change "addInterest" function like this:
$scope.addInterest = function () {
if ($scope.interestLimit) return;
var element = $document[0].getElementById('tagInsert'),
value = element.value.split(',');
if (value.length) {
element.value = '';
for (var i = 0; i < value.length; i++) {
if ($scope.interestLimit) break;
if ($scope.user.interests.indexOf(value[i]) === -1) {
$scope.user.interests.push(value[i]);
$scope.interestLimit = $scope.user.interests.length === 10;
}
}
}
};
As far as I understand , you want to split text into string array by comma
Try this code please
<input id='tags' type="text" />
<input type="button" value="Click" onclick="seperateText()" />
<script>
function seperateText(){
var text= document.getElementById("tags").value;
var tags = text.split(',');
console.log(text);
console.log(tags);
}
</script>

Categories

Resources