Change HTML tag with Javascript - javascript

I asking the user to select given emails, and getting them with javascript from a form on click.
If I have an href like
And I have a bunch of checkboxes for every email obtained from the database
Using javascript, how can I add this value into the emails="" tag by clicking the checkbox?

You can listen to change event for each checkbox to keep track of checked emails:
var boxes = document.querySelectorAll('input[name=email]');
var link = document.getElementById('myHref');
var emails = [];
boxes.forEach(box => box.addEventListener('change', function(e) {
var v = e.target.value;
if (e.target.checked === true) {
if (!emails.includes(v)) emails.push(v);
} else {
emails.splice(emails.indexOf(v), 1);
};
link.setAttribute('emails', emails.join(', '));
console.log(link.attributes.emails.value)
}))
<input type="checkbox" value="1#d.com" name="email">
<input type="checkbox" value="2#d.com" name="email">
<input type="checkbox" value="3#d.com" name="email">
Link

You can set a click event on the checkbox.
var arr_el = document.getElementsByClassName('check-boxes');
for(var i = 0; i < arr_el.length; i++){
arr_el[i].addEventListener('click', function(){
var el = document.getElementById('myHref');
var emails = el.getAttribute('emails');
var userSelectedEmail = this.value;
if(this.checked){
el.setAttribute('emails', emails + ';' + userSelectedEmail);
} else {
// debugger;
emails = emails.split(';');
var index = emails.indexOf(userSelectedEmail);
emails.splice(index, 1);
el.setAttribute('emails', emails.join(';'));
}
document.getElementById('emails').innerText = el.getAttribute('emails');
});
}
<html>
<head>
</head>
<body>
<a id="myHref" href="#" emails="test#email.com">Link</a>
<br>
<input class="check-boxes" type="checkbox" value="email2#gmail.com">email2#gmail.com<br>
<input class="check-boxes" type="checkbox" value="email3#gmail.com">email3#gmail.com<br>
<input class="check-boxes" type="checkbox" value="email4#gmail.com">email4#gmail.com<br>
<input class="check-boxes" type="checkbox" value="email5#gmail.com">email5#gmail.com<br>
<p id="emails"></p>
</body>
</html>

Related

Checkbox selection based on name is prompting other checkbox options

I am attempting to set the value of newStatus or usedStatus if any of the options for either is selected, but for only the ones that are selected.
As of now, if you select "New mowers" and then click on one of its options, you will see in the console that New Selection1 and Used Selection is displayed in the console. For this example and the functionality, only New Selection1 should be showing.
The following if statements are controlling it:
if ("input:checkbox[name=newMowerOption]:checked") {
newStatus = '1';
console.log('New Selection' + newStatus);
}
if ("input:checkbox[name=usedMowerOption]:checked") {
usedStatus = '1';
console.log('Used Selection' + usedStatus);
}
You can see that I am checking for the specific checkboxes based on the name, so I am unsure why if you select a new mower option that the used is also selected.
Anyone have an idea?
var newStatus = ''; //Telling whether new is selected
var usedStatus = ''; //Telling whether used is selected
var newSelPush = '';
var usedSelPush = '';
$('.equipmentOptionCont').change(function() {
var newSel = [];
var usedSel = [];
//Get new mower options
$("input:checkbox[name=newMowerOption]:checked").each(function(){
newSel.push($(this).val());
newSelPush = newSel.join(', ');
});
//Get used mower options
$("input:checkbox[name=usedMowerOption]:checked").each(function(){
usedSel.push($(this).val());
usedSelPush = usedSel.join(', ');
});
//Find out if new/used mower option is selected and then create variable showing 1 if true
if ("input:checkbox[name=newMowerOption]:checked") {
newStatus = '1';
console.log('New Selection' + newStatus);
}
if ("input:checkbox[name=usedMowerOption]:checked") {
usedStatus = '1';
console.log('Used Selection' + usedStatus);
}
$('#newSel').html(newSelPush);
$('#usedSel').html(usedSelPush);
});
$('#newAllOptions').click(function() {
$('input[name=newMowerOption').toggle().prop('checked', true);
});
$('#usedAllOptions').click(function() {
$('input[name=usedMowerOption').toggle().prop('checked', true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>New Mowers</label>
<input type="radio" name="notifymethod" id="newMowerSelect" class="equipmentMainSel">
<label>Used Mowers</label>
<input type="radio" name="notifymethod" id="usedMowerSelect" class="equipmentMainSel">
<div id="newMowerOptions" class="equipmentOptionCont">
<p>New Mower Options</p>
<label>Ferris</label>
<input type="checkbox" name="newMowerOption" value="Ferris">
<label>Wright</label>
<input type="checkbox" name="newMowerOption" value="Wright">
</div>
<div id="usedMowerOptions" class="equipmentOptionCont">
<p>Used Mower Options</p>
<label>Toro</label>
<input type="checkbox" name="usedMowerOption" value="Toro">
<label>John Deere</label>
<input type="checkbox" name="usedMowerOption" value="John Deere">
</div>
Changed logic to get the desired results.
var newStatus = ''; //Telling whether new is selected
var usedStatus = ''; //Telling whether used is selected
var newSelPush = '';
var usedSelPush = '';
$('.equipmentOptionCont').change(function() {
var newSel = [];
var usedSel = [];
//Get new mower options
$("input:checkbox[name=newMowerOption]:checked").each(function(){
newSel.push($(this).val());
newSelPush = newSel.join(', ');
});
//Get used mower options
$("input:checkbox[name=usedMowerOption]:checked").each(function(){
usedSel.push($(this).val());
usedSelPush = usedSel.join(', ');
});
var radioSelID = $("input:radio[name=notifymethod]:checked").attr('id');
if(newSel.length && radioSelID == "newMowerSelect") {
newStatus = '1';
console.log('New Selection' + newStatus);
}
if(usedSel.length && radioSelID == "usedMowerSelect") {
usedStatus = '1';
console.log('Used Selection' + usedStatus);
}
$('#newSel').html(newSelPush);
$('#usedSel').html(usedSelPush);
});
$('#newAllOptions').click(function() {
$('input[name=newMowerOption').toggle().prop('checked', true);
});
$('#usedAllOptions').click(function() {
$('input[name=usedMowerOption').toggle().prop('checked', true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>New Mowers</label>
<input type="radio" name="notifymethod" id="newMowerSelect" class="equipmentMainSel">
<label>Used Mowers</label>
<input type="radio" name="notifymethod" id="usedMowerSelect" class="equipmentMainSel">
<div id="newMowerOptions" class="equipmentOptionCont">
<p>New Mower Options</p>
<label>Ferris</label>
<input type="checkbox" name="newMowerOption" value="Ferris">
<label>Wright</label>
<input type="checkbox" name="newMowerOption" value="Wright">
</div>
<div id="usedMowerOptions" class="equipmentOptionCont">
<p>Used Mower Options</p>
<label>Toro</label>
<input type="checkbox" name="usedMowerOption" value="Toro">
<label>John Deere</label>
<input type="checkbox" name="usedMowerOption" value="John Deere">
</div>
Old answer:
Your if statements were just checking a string, which in JavaScript was always returning true and thus both were being printed. I changed it to check the actual property instead, there a couple different ways to do this but the following does what you want.

How to get the selected radio buttons value?

i am trying to get the value of selected radio buttons so i can submit my form using Ajax i searched here for some help but i couldn't find any useful solution
<input type="radio" id="answer" name="answer<?php echo $function::escape_string($question_row->question_id); ?>"
value="<?php echo $function::escape_string($answer_row>answer_id); ?>"/>
-HTML Output
<input type="radio" id="answer" name="answer16" value="107"/>
<input type="radio" id="answer" name="answer17" value="109"/>
<input type="radio" id="answer" name="answer15" value="104"/>
i found this function here
function findSelection(field) {
var test = document.getElementsByName(field);
var sizes = test.length;
alert("Size is " + sizes);
for (i=0; i < sizes; i++) {
if (test[i].checked==true) {
alert(test[i].value + ' you got a value');
return test[i].value;
}
}
}
var radioinputs = findSelection("answer");
But I do not know what to change so I can make it work with me properly
You can structure like this:
function findSelection(field) {
var test = document.getElementsByClassName(field);
var sizes = test.length;
//alert("Size is " + sizes);
result = [];
// result[16]=107;
// result[17]=109;
// result[15]=104;
for (i=0; i < sizes; i++) {
var index = test[i].dataset.index;
if(test[i].checked == true){
result[index] = test[i].value;
}else{
result[index] = undefined; // for a answer doesn't have a value
}
}
return result;
}
function checkfunction(){
var radioinputs = findSelection("radioanswer");
console.log(radioinputs);
console.log(radioinputs[15]);
};
<form id="form1">
<input type="radio" class="radioanswer" name="answer16" data-index="16" value="107"/>
<input type="radio" class="radioanswer" name="answer17" data-index="17" value="109"/>
<input type="radio" class="radioanswer" name="answer15" data-index="15" value="104"/>
<button type="button" onclick="checkfunction();"> Check </button>
</form>
A class can has multiple instances, but id has only one! And you can see document about data attributes here: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
From the looks of it you have a dynamic name field, i.e. name="answer2", name="answer3", etc. Because of that your query document.getElementByName(field) will not find a field matching "answer".
To remedy this either get rid of the dynamic name or if you really need it then I would say add a class to all those radio buttons and use document.getElemenetsByClassName.

JavaScript form same values

How can I make a form so they cannot repeat the same values in the Input?
I tried a way like:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num1').value;
var textform = [text1,text2];
if (
text1 == text2 ||
text2 == text1
) {
alert("repeated numbers");
return false;
}
But this is gets me into two troubles:
- If I put no value, it will say: Repated Numbers
- If I want to make this for 100 form values, it takes a lot of code
You could give all of your text elements the same class, and grab their values by class name to simplify building the array of text values.
<input type="text" class="checkDupe" id="input1" />
<input type="text" class="checkDupe" id="input2" />
Then grab their values in javascript
var checkDupes = document.getElementsByClassName('checkDupe');
var textArray = [];
for(var i = 0; i < checkDupes.length; i++){
textArray.push(checkDupes[i].value);
}
Now that we have an array of values that they entered, check to see if any of them repeat by sorting the array, and seeing if any two elements side-by-side are the same.
textArray.sort();
var dupes = false;
for(var i = 0; i < textArray.length; i++){
if(textArray[i] === textArray[i + 1]) dupes = true;
}
If we find any duplicates, let the user know.
if(dupes) alert('Repeated numbers!');
You could do something like this:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num2').value;
var textform = [text1, text2];
var seen = {};
textform.forEach(function(value) {
if (seen[value]) {
alert('Bad!');
}
seen[value] = true;
});
In the code above, we loop over each value in the array. The first time we encounter it, we push it into a map. Next time (if) we hit that value, it will exist in the map and it will tell us we've seen it before.
If you give all the input's a common class then you quickly loop through them.
The HTML:
<input type="text" name="num1" class="this that number"></input>
<input type="text" name="num2" class="this number"></input>
<input type="text" name="num3" class="that number"></input>
<input type="text" name="num4" class="number"></input>
<input type="text" name="num5" class=""></input> <!-- we don't want to check this one -->
<input type="text" name="num6" class="number that this"></input>
<input type="text" name="num7" class="this that number"></input>
The JavaScript:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then let the user know they are a bad person
// and stop
if(tracker[inValue])
{
alert("You are a bad person!");
return;
}
// track the value
tracker[inValue] = true;
}
You could also enhance this to let the user know which inputs have duplicate values:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then error them
if(tracker[inValue])
{
// mark the current input as error
ins[i].className += " error";
// mark the first found instance as an error
ins[tracker[inValue]].className += " error";
}
// save the index so we can get to it later if a duplicate is found
tracker[inValue] = i;
}
Here's a way of doing it that automatically picks up all the text inputs in your document and validates based on what you're looking for. Would be simple enough to expose the valid value and make this the validation handler (or part of one) that handles a form submission.
<meta charset="UTF-8">
<input id="num1" type="text" value="foobar1">
<input id="num2" type="text" value="foobar2">
<input id="num3" type="text" value="foobar3">
<input id="num4" type="text" value="foobar4">
<input id="num5" type="text" value="foobar5">
<button onClick="checkValues();">Validate</button>
<script>
function checkValues() {
var inputs = document.getElementsByTagName('input');
arrInputs = Array.prototype.slice.call(inputs);
var valid = true;
var valueStore = {};
arrInputs.forEach(function(input) {
if (input.type == 'text') {
var value = input.value.toUpperCase();
if (valueStore[value]) {
valid = false;
} else {
valueStore[value] = true;
}
}
});
if (valid) {
alert('Valid: No matching values');
} else {
alert('Invalid: Matching values found!');
}
}
</script>
With jquery you can iterate directly over the inputs.
<form>
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<button>
TEST
</button>
</form>
function checkValues(){
var used = {};
var ok = true;
$('form input[type="text"]').each(function(){
var value = $(this).val();
if(value !== ""){
if(used[value] === true){
ok = false;
return false;
}
used[value] = true;
}
});
return ok;
}
$('button').click(function(event){
event.preventDefault();
if(!checkValues()){
alert("repeated numbers");
};
});
https://jsfiddle.net/8mafLu1c/1/
Presumably the inputs are in a form. You can access all form controls via the form's elements collection. The following will check the value of all controls, not just inputs, but can easily be restricted to certain types.
If you want to include radio buttons and checkboxes, check that they're checked before testing their value.
function noDupeValues(form) {
var values = Object.create(null);
return [].every.call(form.elements, function(control){
if (control.value in values && control.value != '') return false;
else return values[control.value] = true;
});
}
<form id="f0" onsubmit="return noDupeValues(this);">
<input name="inp0">
<input name="inp0">
<input name="inp0">
<button>Submit</button>
</form>
For old browsers like IE 8 you'll need a polyfill for every.
You can simply get all inputs iterate them twice to check if they are equals
var inputs = document.getElementsByTagName('input');
for (i = 0; i < inputs.length; i++) {
for (j = i + 1; j < inputs.length; j++) {
if (inputs[i].value === inputs[j].value) {
console.log('value of input: ' + i + ' equals input: ' + j);
}
}
}
<input value="56" />
<input value="12" />
<input value="54" />
<input value="55" />
<input value="12" />

implementing insertbefore() in loop

I am trying to show error messages below an array of textboxes that I have selected using Javascript. The error messages are being put by creating a new span element and using the insertBefore() method. The span element is created in the function since I don't want to hard code it into the DOM. The span messages do show but each time I submit the form, they are appended over and over again. I'd like to show the span messages only once and each time the form is submitted, they are shown once only. Below is my code.
HTML
<div class="slideshow">
<form id="form">
<input type="text" name="1" class="textbox" />
<input type="text" name="2" class="textbox" />
<input type="text" name="3" class="textbox" />
<input type="submit" name="submit" value="submit" id="submit" />
</form>
</div>
JAVASCRIPT
<script>
var slideshow = document.querySelector('.slideshow');
// var span = document.createElement('span');
var form = document.querySelector('#form');
var inputs = form.querySelectorAll('.textbox');
form.addEventListener('submit', function(e)
{
e.preventDefault();
for( var i=0; i<inputs.length; i++ )
{
var span = document.createElement('span');
(function(index)
{
span.innerHTML = 'error ' + index;
inputs[index].parentNode.insertBefore(span, inputs[index].nextElementSibling);
})(i);
}
}, false);
</script>
Each time I submit, I'd like the error messages to be shown below the textbox and not appended over and over again. They should be shown just once and I'd like to do this without using jQuery or any sort of library.
I rewerite your example to create available 3 span tags instead of crate them in code. If there are some errors, populate them to span rather than creating/deleting the spans in code.
var slideshow = document.querySelector('.slideshow');
var form = document.querySelector('#form');
var inputs = form.querySelectorAll('.textbox');
form.addEventListener('submit', function (e) {
e.preventDefault();
for (var i = 0; i < inputs.length; i++) {
(function (index) {
document.getElementsByTagName('span')[index]
.innerHTML = 'error ' + index;
})(i);
}
}, false);
<div class="slideshow">
<form id="form">
<input type="text" name="1" class="textbox" /><span></span>
<input type="text" name="2" class="textbox" /><span></span>
<input type="text" name="3" class="textbox" /><span></span>
<input type="submit" name="submit" value="submit" id="submit" />
</form>
</div>
Hope this help.
Just do a check before you insert. Here is one way to do it.
form.addEventListener('submit', function (e) {
e.preventDefault();
for (var i = 0; i < inputs.length; i++) {
var span = document.createElement('span');
(function (index) {
span.innerHTML = 'error ' + index;
if (inputs[index].nextElementSibling.tagName !== 'SPAN')
inputs[index].parentNode.insertBefore(span, inputs[index].nextElementSibling);
})(i);
}
}, false);
You have to wait for page to be load, the you should run JavaScript.
PageLoad Event : window.onload=function(){}
Code :
<script type="text/javascript">
window.onload = function () {
var slideshow = document.querySelector('.slideshow');
var form = document.getElementById('form');
var inputs = document.querySelectorAll('.textbox');
form.addEventListener('submit', function (e) {
e.preventDefault();
for (var i = 0; i < inputs.length; i++) {
var span = document.createElement('span');
(function (index) {
span.innerHTML = 'error ' + index;
inputs[index].parentNode.insertBefore(span, inputs[index].nextElementSibling);
})(i);
}
}, false);
}
</script>
Put your code in window.onload event.

Delete form fields using Javascript

Is it possible to write a Javascript function to delete form a field when somebody does not fill in the field?
<form id="myform">
<label for="q1" id="q1label">question 1</label>
<input type="text" id="q1" name="q1"/>
<label for="q2" id="q2label">question 2</label>
<input type="text" id="q2" name="q2"/>
<label for="q3" id="q3label">question 3</label>
<input type="text" id="q3" name="q3"/>
<input type="submit" value="Delete blank fields" onclick="return checkanddelete"/>
</form>
If somebody does not fill in question 2 for example, it deletes question 2 label and the field.
For jQuery:
<script type="text/javascript">
function checkanddelete() {
$('input').each(function(){
if ($(this).val() == '') {
var id = $(this).attr('id');
$.remove('#' + id);
$.remove('#' + id + 'label');
}
});
}
</script>
For JavaScript:
<script type="text/javascript">
function checkanddelete() {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++)
{
if (document.getElementsByTagName("input")[i].value.length == 0) {
var id = document.getElementsByTagName("input")[i].id;
(elem=document.getElementById(id)).parentNode.removeChild(elem);
(elem=document.getElementById(id + 'label')).parentNode.removeChild(elem)
}
}
}
</script>
Something like this?
With jquery:
$("#myform :text").each(function(){
if( !$.trim($(this).val()) )
$(this).prev('label').andSelf().remove();
});
i am using folloing function to remove element from document.
function removeElement(id)
{
if(typeof id === "object")
return id.parentNode.removeChild(id);
else
return (elem=document.getElementById(id)).parentNode.removeChild(elem);
}
You can pass a dom element or element Id itself to delete .
The following should do what you want :
var inputToDelete = document.getElementById("q2");
if (inputToDelete.value == "") {
var labelToDelete = document.getElementById("q2label");
var parentNode = document.getElementById("myform");
parentNode.removeChild(labelToDelete);
parentNode.removeChild(inputToDelete);
}

Categories

Resources