Create elements based on checkbox selection - javascript

I have this HTML:
<fieldset style="" title="Variaciones" id="product-create-step-3" class="fstep">
<legend>Variaciones</legend>
<section id="choices">
<input type="checkbox" value="24" id="24" name="Size"> Size
<input type="checkbox" value="25" id="25" name="Color"> Color
<section style="display: none" class="options_holder"></section>
<section style="display: none" class="variations_holder"></section></section>
</fieldset>
I need to create some input based on what checkbox/es was marked. For example if I mark first one 'Size' I should obtain this:
<section style="display: none" class="options_holder">
<input name="size[24][]" value="" placeholder="Write your size" />
</section>
if I mark second one 'Color' I should obtain this:
<section style="display: none" class="options_holder">
<input name="color[25][]" value="" placeholder="Write your color" />
</section>
if I mark both 'Size' & 'Color' I should obtain this:
<section style="display: none" class="options_holder">
<input name="size[24][]" value="" placeholder="Write your size" />
<input name="color[25][]" value="" placeholder="Write your color" />
</section>
How I would do that?
UPDATE 1
I'm trying to get which checkbox was checked by doing this:
$("#choices :checked").each(function() {
console.log(this.id + "was checked");
});
But it's not working
UPDATE 2
I realize into another problem, how I check when a checkbox was checked and after trigger some code without know any data of the checkbox? I have a code that generates check-boxes on the fly so I'll never know their name's or id's or any other data. My template for that creation looks like this:
<input type="checkbox" name="{{ entity.getLabel|lower }}" id="{{ entity.getLabel|lower ~ "_choice" }}" value="{{ entity.getId }}" /> {{ entity.getLabel }}
Where for example name could take "color" and in that case id will be "color_choice" or name could take "size" and in that case id will be "size_choice", sometimes one is created some time both are created. What I need to know and I don't is how to know which check-box was checked and when trigger some event as for example create some others input's on the fly. How do I deal with this part too?

So, your javascript should work if you change your selector to include the element that uses the pseudo-selector:
$("#choices input:checked").each(function() {
console.log(this.id + "was checked");
});
As for accessing the attribute values, you can use either the native javascript object that you're using, i.e.:
console.log("value is " + this.value);
Or you can use jQuery's attr()
console.log("name is " + $(this).attr('name'))
A working example showing both cases, as well as having attached the event to any click of input items is at this jsfiddle:
http://jsfiddle.net/k3B73/

<fieldset style="" title="Variaciones" id="product-create-step-3" class="fstep">
<legend>Variaciones</legend>
<section>
<input type="checkbox" value="24" id="24" name="Size" id='size_choice'> Size
<input type="checkbox" value="25" id="25" name="Color" id='color_choice'> Color
<section style="display: none" class="options_holder" id='options_holder'></section>
<section style="display: none" class="variations_holder"></section>
</section>
</fieldset>
<script type="text/javascript">
$(document).ready(function(){
$('#size_choice').click(function(){
if ($(this).is(':checked'))
$("#options_holder").append('<input name="size[24][]" value="" placeholder="Write your size" id="size" />');
else
$("#size").destroy();
});
$('#color_choice').click(function(){
if ($(this).is(':checked'))
$("#options_holder").append('<input name="color[25][]" value="" placeholder="Write your color" id="choice" />');
else
$("#color").destroy();
});
})
</script>

Related

Find the nearest id in javascript

I have two divs
<div class="maca">
<input type="hidden" value="1">
<div onclick="removeInput(nearest input type hidden)">Remove</div>
</div>
<div class="maca">
<input type="hidden" value="1">
<div onclick="removeInput(nearest input type hidden)">Remove</div>
</div>
I want to send as a parameter the value of nearest input type hidden of that div that we are clicking on
Im not 100% sure what you mean with nearest but with this you get the input hidden inside the div. By the way you could also put the element.parentNode.querySelector into the onclick but personally i like it more to split HTML and JS.
function removeInput(element){
let value = element.parentNode.querySelector("input[type='hidden']").value;
console.log(value);
}
<div class="maca">
<input type="hidden" value="1">
<div onclick="removeInput(this)">Remove</div>
</div>
<div class="maca">
<input type="hidden" value="5">
<div onclick="removeInput(this)">Remove</div>
</div>
You can send the event as a parameter to a javascript function and then find the input via the parentNode. This isn't a literal interpretation of your question since faithfully the "nearest" element is rather complex and probably not what you're looking for.
function removeInput(e) {
const nearestInput = e.target.parentNode.querySelector("input[type='hidden']");
console.log(nearestInput);
}
<div class="maca">
<input type="hidden" value="1" />
<div onclick="javascript:removeInput(event)">Remove</div>
</div>
<div class="maca">
<input type="hidden" value="1" />
<div onclick="javascript:removeInput(event)">Remove</div>
</div>
You should not use inline event listeners, which are widely considered bad practice.
Instead, use addEventListener to add the click listeners, and find the input (given your markup structure is fix like you've shown) using previousElementSibling:
for (const remover of document.querySelectorAll('.remove-input')) {
remover.addEventListener('click', () => remover.previousElementSibling.remove(), { once: true });
}
<div class="maca">
<input type="hidden" value="1" />
<div class="remove-input">Remove</div>
</div>
<div class="maca">
<input type="hidden" value="1" />
<div class="remove-input">Remove</div>
</div>

Form field showing

This mostly works. It shows the SSN when the first Val radio button is picked. It also shows the PaperAppliction when the second Val radio button is picked. The ONLY problem is that the field PaperApplication shows when the form is loaded before any radio buttons are picked. I need it to hide both SSN and PaperApplicaition until one of the radio buttons is picked, and then show the proper field. What am I missing?
Here is the JS
$(".field.SocialSecurity input[type=radio]").on("change", function() {
if (
$(this).val() ==
"As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number."
) {
$(".field.SSN").show();
$(".field.SSN input").focus();
$(".field.PaperApplication").hide();
} else if (
$(this).val() ==
"Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number."
) {
$(".field.PaperApplication").show();
$(".field.PaperApplication input").focus();
$("field.SSN").hide();
} else {
$("field.PaperApplication").hide();
}
});
Here is the form html
US Citizen International Student Other
<div class="field SSN">
<label>SSN</label>
<input />
</div>
<div class="field PaperApplication">
<label>Paper Application</label>
<input />
</div>
You can just set them hidden initially using HTML markup to add a style attribute to the element. style="display:none" should do it.
e.g. <div class="field SSN" style="display:none;"> and the same for the other one.
Hide them both when the script is called, and also outside of the if statements when the change event is fired. Also, make your radio button values a word or two, camelCased. Put the string describing the button in the label tag:
$(".SSN, .PaperApplication").hide();
$(".field.SocialSecurity input[type=radio]").on("change", function() {
$(".SSN, .PaperApplication").hide();
if ($(this).val() == "first") {
$(".field.SSN").show();
$(".field.SSN input").focus();
} else if ($(this).val() == "second") {
$(".field.PaperApplication").show();
$(".field.PaperApplication input").focus();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="field SocialSecurity">
<label>
Radio 1 text here
<input type="radio" name="radio" value="first" />
</label><br>
<label>
Radio 2 text here
<input type="radio" name="radio" value="second" />
</label>
</div>
<div class="field SSN">
<label>SSN</label>
<input />
</div>
<div class="field PaperApplication">
<label>Paper Application</label>
<input />
</div>
hide on load, then on click hide both and show the one that was clicked. run below snippet
$("input[name='socialsecurity']").click(() => {
$('.field').hide();
$(`.${$("input[name='socialsecurity']:checked").val()}`).show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="socialsecurity" value="SSN"> SSN<br>
<input type="radio" name="socialsecurity" value="PaperApplication"> Paper Application<br>
<div class="field SSN" style = 'display: none;'>
<label>SSN</label>
<input />
</div>
<div class="field PaperApplication" style = 'display: none;'>
<label>Paper Application</label>
<input />
</div>

How to get JQuery closest input id and data-attr?

I have multiple input fields in my form that use the Add button. I have created my button with an image tag. Each image tag has the same class. Once I click on the image I want to get the id of my closest input field as well as data attribute value. Here is example of my HTML:
<div class="formItem">
<label for="status">Status:</label>
<input type="text" name="ls_status" id="ls_status" value="" data-master="STATUS" size="10" maxlength="10" readonly />
<img src="Images/add.png" alt="Click to add value" class="masterRecords" />
</div>
<div class="formItem">
<label for="age">Age:</label>
<input type="text" name="ls_age" id="ls_age" value="" data-master="AGE" size="10" maxlength="10" readonly />
<img src="Images/add.png" alt="Click to add value" class="masterRecords" />
</div>
Here is what I tried in JQuery:
$('.masterRecords').on('click', function(){
console.log($(this).closest('input').prop('id'));
});
In my debugging console I see 'undefined' only. First of all I'm not sure if I approached the best way to solve this problem. I repeat there is multiple elements that use the same class and I need to pull ID and data for each of them. They are all in separate div containers as you can see in my example above. If anyone see where is bug in my code please let me know. Also I would like to hear some suggestions if there is better way to do this with JQuery/HTML5/CSS3. Thank you.
Try using siblings instead of closest.
$('.masterRecords').on('click', function(){
console.log($(this).siblings('input').prop('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="formItem">
<label for="status">Status:</label>
<input type="text" name="ls_status" id="ls_status" value="" data-master="STATUS" size="10" maxlength="10" readonly />
<img src="https://i.stack.imgur.com/Qo01e.png" alt="Click to add value" class="masterRecords" />
</div>
<div class="formItem">
<label for="age">Age:</label>
<input type="text" name="ls_age" id="ls_age" value="" data-master="AGE" size="10" maxlength="10" readonly />
<img src="https://i.stack.imgur.com/Qo01e.png" alt="Click to add value" class="masterRecords" />
</div>
Solution: https://jsfiddle.net/jdjc1bc7/
$('.masterRecords').on('click', function(){
console.log($(this).siblings('input').prop('id'));
});
You can check for input in siblings, since in your current DOM the inputs are sibling to the element which is being clicked.
This should be the fastest way for you. https://jsperf.com/jquery-siblings-vs-parent-find-vs-find
If your structure will always be like this, you could also retrieve your related input with
$('input', $(this).parent())
which will return all inputs in the same div as the image
Because input is to the left of you can find it like this:
$('.masterRecords').on('click', function(){
console.log($(this).prev('input').prop('id'));
});
If input was after button then you can find it like this:
$('.masterRecords').on('click', function(){
console.log($(this).next('input').prop('id'));
});
Then for data attribute value just use .data or .attr of ID value you get:
$('#'+ID).attr('data-master');
$('.masterRecords').on('click', function(){
var inputTextId = $(this).prev('input').prop('id');
console.log(inputTextId);
console.log($('#'+inputTextId).attr('data-master'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="formItem">
<label for="status">Status:</label>
<input type="text" name="ls_status" id="ls_status" value="" data-master="STATUS" size="10" maxlength="10" readonly />
<img src="Images/add.png" alt="Click to add value" class="masterRecords" />
</div>
<div class="formItem">
<label for="age">Age:</label>
<input type="text" name="ls_age" id="ls_age" value="" data-master="AGE" size="10" maxlength="10" readonly />
<img src="Images/add.png" alt="Click to add value" class="masterRecords" />
</div>
The <INPUT/> element is not an ancestor of your image. Try:
$('.masterRecords').on('click', function(){
console.log($(this).closest(".formItem").find('input').attr('id'));
});

Getting label text of checkbox and appending to div

Working on revamping some old code and needing some help on this last addition. Basically can have a variable number of checkboxes and need to get the labels text to any of those checkboxes and append that text to another div. Have rewritten this a ton of times and used a lot of others code but nothing seems to be working. Have seen several similar questions on here but none of those have worked for a solution to this problem.
Problem:
Get a labels text associated to it's input checkbox. Then once that text value is gathered append it to a separate div.
Note:
The checkboxes have an ID and a VALUE that are the same because of some different code versions just trying to get them to work. Would like a solution using VALUE only.
HTML:
<a cid="38" href="javascript:void(0);" class="cat_filter">
<div class="cat-filter_checkbox">
<input class="cat_filter_checkbox" name="" type="checkbox" value="38" id="38">
<label for="38">Category ONE</label>
</div>
</a>
<a cid="14" href="javascript:void(0);" class="cat_filter">
<div class="cat-filter_checkbox">
<input class="cat_filter_checkbox" name="" type="checkbox" value="14" id="14">
<label for="14">Category TWO</label>
</div>
</a>
<div id="labelName"></div>
JS:
$(".cat_filter").live('click', function() {
$(this).find("input:checkbox").attr("checked", true);
var labelName = $(this).find("label[for='"+$(this).attr("id")+"']").text();
labelName.appendTo('#labelName');
});
Fiddle:
http://jsfiddle.net/wfuller/o25z9w0f/1/
Any help would be greatly appreciated.
So this should solve your problem:
$(".cat_filter").on('click','input',function() {
//On click on an input field. if this isn't OK tell me and I will change it again.
$('#labelName').html($('label[for='+$(this).prop('id')+']').html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a cid="38" href="javascript:void(0);" class="cat_filter">
<div class="cat-filter_checkbox">
<input class="cat_filter_checkbox" name="" type="checkbox" value="38" id="38">
<label for="38">Category ONE</label>
</div>
</a>
<a cid="14" href="javascript:void(0);" class="cat_filter">
<div class="cat-filter_checkbox">
<input class="cat_filter_checkbox" name="" type="checkbox" value="14" id="14">
<label for="14">Category TWO</label>
</div>
</a>
<div id="labelName"></div>
Greetings from Vienna
var nodeList = document.querySelectorAll('input[type ="checkbox"]');
var div = document.getElementById('myDiv');
for (node in nodeList) {
div.innerHTML += node.text; //or label if you set that attribute on the element
}
Does not rely on jQuery

Jquery how to check checkbox on div click, change class and show div

I am trying to checkbox when the div.menuitem is clicked and then it should change class and show the content in the div with class of hidediv. When the div.menuitem is again clicked it should remove the class and hide the div again and uncheck the checkbox.
Want I want to do:
Only show the content of the hidediv when the menuitem is pressed. (checkbox should be checked)
When the menuitem is pressed the checkbox should be checked
When the menuitem is clicked again the hidediv should be hidden again. (checkbox unchecked)
And the checkbox should be uncheched
Illustration of my menu form:
<div class="menuitem">
1.Company1
</div>
<div class="hidediv">
1.1 Company 1.1
1.2 Company 1.2
</div>
<div class="menuitem">
1.Company2
</div>
<div class="hidediv">
1.1 Company 2.1
1.2 Company 2.2
</div>
My previous Jquery code, which only is trigger when the checkbox is clicked. I want pretty
similar function to this, the checkbox should also be trigghed when the div is clicked:
$('.menuitem input:checkbox').change(function(){
if($(this).is(':checked')) {
$('div.hidediv').addClass('someclass').show(200); // not needed it there is another way of identifying the div later to add to hidediv class again.
$('div.hidediv').removeClass('hidediv');
} else {
$('div.someclass').addClass('hidediv').hide(200);
}
});
});
My Jquery so far(not working):
$('.menuitem').click(function(e){
$(this).addClass('menuclicked');
$('div.hidediv').addClass('clicked').show(200);
$('div.hidediv').removeClass('hidediv');
} else {
$('div.someclass').addClass('hidediv').hide(200);
}
$('.menuclicked').click(function(e){
$('div.someclass').addClass('hidediv').hide(200);
});
My HTML:
<form accept-charset="UTF-8" action="/" method="get"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /></div>
<div class="menuitem">
<label for="search_company1">company1</label>
<input name="search[company1_is_true]" type="hidden" value="0" /><input id="search_company1_is_true" name="search[company1_is_true]" type="checkbox" value="1" />
</div>
<div class="menuitem">
<label for="search_company3">company3</label>
<input name="search[company3_is_true]" type="hidden" value="0" /><input id="search_company3_is_true" name="search[company3_is_true]" type="checkbox" value="1" />
</div>
<div class="hidediv">
<div class="menuitem">
<label for="search_company2">company2</label>
<input name="search[company2_is_true]" type="hidden" value="0" /><input id="search_company2_is_true" name="search[company2_is_true]" type="checkbox" value="1" />
<div>
</div>
<input id="search_submit" name="commit" style="display:none;" type="submit" value="Submit" />
</form>
I can help. I think you are structuring this wrong. You have three fields in your html, with the third being hidden. I assume when you fill in the first one you want nothing to happen, but clicking the second one should show the third field?
Try this:
//Use toggle instead of .click()
$('.menuitem').toggle(function(){
$('div.hidediv').addClass('clicked').show(200);
}, function(){
$('div.hidediv').removeClass('clicked').hide(200);
});
This will effect all divs with the "menuitem" class, meaning when you click on any of the three it will toggle showing/hiding the div with the "hidediv" class.
edit you have a couple valid answers here, but I think you're approaching this wrong. If you go try the jsfiddle posted by another user, whos' javascript does the same as mine - it reveals the problem I talked about above. You cannot select all three boxes without some clever clicking. Each click will toggle showing/hiding the third check box. Might I suggest modifying your code like so:
//Use toggle instead of .click()
$('.toggleMenuItem').toggle(function(){
$('div.hidediv').addClass('clicked').show(200);
}, function(){
$('div.hidediv').removeClass('clicked').hide(200);
});
<form accept-charset="UTF-8" action="/" method="get">
<div style="margin:0;padding:0;display:inline">
<input name="utf8" type="hidden" value="✓" />
</div>
<div class="menuitem">
<label for="search_company1">company1</label>
<input name="search[company1_is_true]" type="hidden" value="0" />
<input id="search_company1_is_true" name="search[company1_is_true]" type="checkbox" value="1" />
</div>
<div class="menuitem toggleMenuItem">
<label for="search_company3">company3</label>
<input name="search[company3_is_true]" type="hidden" value="0" />
<input id="search_company3_is_true" name="search[company3_is_true]" type="checkbox" value="1" />
</div>
<div class="hidediv">
<div class="menuitem">
<label for="search_company2">company2</label>
<input name="search[company2_is_true]" type="hidden" value="0" />
<input id="search_company2_is_true" name="search[company2_is_true]" type="checkbox" value="1" />
<div>
</div>
<input id="search_submit" name="commit" style="display:none;" type="submit" value="Submit" />
</form>
This will make it so only clicking the checkboxes with the class ".toggleMenuItem" will show the third checkbox.
try something like this:
$('.menuitem').click(function(e){
if($(this).hasClass('menuClicked')){
// Already clicked
$(this)
.removeClass('menuclicked')
.html("");
}else{
// First click
$(this)
.addClass('menuclicked');
.html($('#hidediv').html());
}
})
This may do what you're looking for:
$('.menuitem').click(function(e){
$(this).toggleClass('clicked');
$('div.hidediv').toggle(200);
});
Let me know if it is missing a feature.
http://jsfiddle.net/citizenconn/2bCdR/

Categories

Resources