changing checkboxes into animatable buttons with javascript - javascript

I'm building a practice app. I've got a working filter system using checkboxes and radio buttons. I need a way to replace them with buttons that I can animate. For my plunk I'll use buttons with text, but then offline I'll replace them with images. Here's a sample of my work:
HTML
<h2>Type</h2>
<label class="btns">
<input type="radio" name="vegMeat" value="" ng-model="type.searchVeg" ng-checked="true">All
</label>
<label class="btns">
<input type="radio" name="vegMeat" value="veg" ng-model="type.searchVeg">Vegetarian
</label>
<label class="btns">
<input type="radio" name="vegMeat" value="meat" ng-model="type.searchVeg">Meat
</label>
</div>
JavaScript
.filter('searchType', function() {
return function(foods, search) {
var filtered = [];
if (!search) {
return foods;
}
angular.forEach(foods, function(food) {
if (angular.lowercase(food.type).indexOf(angular.lowercase(search)) != -1) {
filtered.push(food);
}
});
return filtered;
};
sample plunk
https://plnkr.co/edit/xk1VcCfAsVknyahux4fw?p=preview
PS I know mine is not the most efficient way of doing it, but I'm still a beginner. The buttons are my main concern but if anyone does have suggestions on how to improve the code itself, please feel free to provide an example. This is just a sample of my plunk. My full one has another 5 sets of buttons and many more recipes.

Related

How to correctly represent true / false when dealing with radio buttons?

I'm trying to wrap my head around this and trying to improve my Javascript ability. I am using ASP.NET Core MVC to create a basic web form and I've got Javascript that will run when a radio button is selected.
Razor
<div class="form-row">
<div class="form-group col-sm-4">
<label class="bold" asp-for="PhoneSetup"></label>
<br />
<input type="radio" asp-for="PhoneSetup" name="PhoneSetup" value="true" onclick="phoneSetupSelect()" /><label>Yes</label>
<input type="radio" asp-for="PhoneSetup" name="PhoneSetup" value="false" onclick="phoneSetupSelect()" /><label>No</label>
</div>
</div>
Javascript
<script>
function phoneSetupSelect() {
var formInput = document.getElementById("myForm");
var phoneSetupValue = formInput.PhoneSetup.value;
//alert(phoneSetupValue);
console.log('phoneSetupValue = ' + phoneSetupValue);
if (phoneSetupValue == 'true') {
document.getElementById('hiddenDiv').classList.remove("hidden");
}
else {
document.getElementById('hiddenDiv').classList.add("hidden");
}
}
</script>
Aside from the if condition shown in the script, I tried the following
if(phoneSetupValue == true) and if(phoneSetupValue)
with mixed results. The former does not work, despite the model property being of type bool and the latter DOES work, which I understand why. In that case, since the same script is attached to both radio buttons, the value being present on either will trigger the true condition.
I got it to work but I'm just confused as to why and if there are ways I can make this better and less "hacky" feeling.

how to update 2 attributes with one radio button?

I'm not sure if I'm just stuck in a jQuery mindset but is there a way to update 2 model attributes with one radio button? Currently I have 2 radio buttons with one hidden. The visible one checks the second with an #click event that gets the next input and sets it to true.
var app = new Vue({
data: {
order: {
amount:
type:
}
},
methods: {
selectType: function(e) {
e.currentTarget.getElementSibling.checked = true;
}
}
});
<form>
<input type="radio" v-model="order.amount" value=15 #click="selectType">$15</input><br>
<input type="radio" v-model="order.type" value="small" style="display:none">
<input type="radio" v-model="order.amount" value=15 #click="selectType">$15</input><br>
<input type="radio" v-model="order.type" value="med" style="display:none" #click="selectType">
<input type="radio" v-model="order.amount" value=20 >$20</input><br>
<input type="radio" v-model="order.type" value="large" style="display:none">
</form>
The way I understand it, the v-model syntax is best for binding a single value. You could try to somehow make the value a JSON string and then decode it... but that sounds like a bad idea. Here are three ideas:
Using JQuery and Vue
Instead, you could give the radio buttons attributes for each value you want, and then parse out those attributes on the click callback. For example:
<input type="radio" name="rad" btn-amount="10" btn-type="small" #click="selectType($event)">$15 <br>
<input type="radio" name="rad" btn-amount="15" btn-type="med" #click="selectType">$15<br>
<input type="radio" name="rad" btn-amount="20" btn-type="large" #click="selectType">$20<br>
and then a method:
selectType: function(e) {
this.order.amount = $(e.currentTarget).attr('btn-amount');
this.order.type = $(e.currentTarget).attr('btn-type');
}
Here's a JSFiddle showing it in action.
Using Vue only
Alternatively, you could move the data for the options into the vue instance, rather than placing them on on the radio buttons. For example, add an options array to the data, and iterate over it in the HTML to create the buttons
<div v-for="option in options">
<input type="radio" name="rad" #click="selectType(option)">${{ option.amount }}
</div>
Notice that you can pass the current option in the for loop to the click handler! That means you can write selectType as:
selectType: function(option) {
this.order = option;
}
This is very clean, and what I recommend if you plan on keeping the radio-button functionality simple.
Here is a JSFiddle showing it in action.
Using Vue Components
But, if you plan on making things more complex you may want to encapsulate the radio button functionality into a component.
Consider the template:
<template id="radio-order">
<div>
<input type="radio" :name="group" #click="setOrder">${{ amount }}
</div>
</template>
and its associated component:
Vue.component('radio-order', {
template: '#radio-order',
props: ['group', 'amount', 'type'],
methods: {
'setOrder': function() {
this.$dispatch('set-order', {
amount: this.amount,
type: this.type
})
}
}
});
Now you can make <radio-order> components that dispatch a set-order event when clicked. The parent instance can listen for these events and act appropriately.
Admittedly, this method is more verbose. But, if you're thinking of implementing more complex functionality, it's probably the way to go.
Here's a JSFiddle of it in action.
Of course, there are many more ways to solve the problem, but I hope these ideas help!

Another way to show and hide buttons

The following codes works with no problem if I am running the file locally on my drive. Unfortunately, I need to upload this form to a software called MasterControl. It does not work. I was wondering if there is another way of coding that is universal to local as well as upload to a server for MasterControl.
The purpose of this code is - once you click on Yes button on the first level question then the next level questions will appear. If you click on No button on the first level and if the questions from the next level questions showing then it will clear all the selected buttons and hide the section of the second level questions.
Here is the codes:
HTML Code:
<div id="divDeathOccurred" class="fieldRow">
<div class="leftLabel labelWidth22">
<label for="">A. Has a death occurred?</label>
</div>
<div class="leftField">
<div class="formField34">
<input id="rbDeathOccurred" name="rbDeathOccurred"
type="radio" class="radiobuttonfield" title="Death Occurred"
value="Yes" onclick="javascript:USAYesNoCheckDO();" />Yes
<input id="rbDeathOccurred" name="rbDeathOccurred"
type="radio" class="radiobuttonfield" title="Death Occurred"
value="No" onclick="javascript:USAYesNoCheckDO();" />No
</div>
</div>
<p> </p>
<div id="USADOYesNo" style="display:none">
<ol type="1" class="indentList">
<li>Is there a reasonable possibility that a device failure
or malfunction was a direct or indirect factor in the death?
<br>
<input id="rbDOYesNo" name="rbDOYesNo" type="radio"
class="USDO radiobuttonfield" title="Yes Reportable" value="Yes"
onclick="javascript:USDeviceFailure30Days();" />
<label for="rbDOYesNo" class="rptColor">Yes -
reportable</label>
<input id="rbDOYesNo" name="rbDOYesNo" type="radio"
class="USDO1 radiobuttonfield" title="No" value="No"
onclick="javascript:USDeviceFailure30Days();" />No - No
Report
<div id="calc" class="indentListCalc">
<input id="dt30Days3" type="text" class="textfieldCalc
labelWidth25" alt="Device Malfunction" />
</div>
<p></p>
</li>
<li>Is there a reasonable possiblity that a device design
defect was direct or indirect factor in the death?
<br>
<input id="rbDOYesNo1" name="rbDOYesNo1" type="radio"
class="USDO2 radiobuttonfield" title="Yes Reportable" value="Yes"
onclick="javascript:USDeviceDesign30Days();"/>
<label for="rbDOYesNo1" class="rptColor">Yes -
Reportable</label>
<input id="rbDOYesNo1" name="rbDOYesNo1" type="radio"
class="USDO3 radiobuttonfield" title="No" value="No"
onclick="javascript:USDeviceDesign30Days();" />No - No Report
<div id="calc1" class="indentListCalc">
<input id="dt30Days1" type="text" class="textfieldCalc
labelWidth25" alt="Device Design" />
</div>
<p></p>
</li>
<li>Is there a reasonable possiblity that the device
labeling was direct or indirect factor in the death?
<br>
<input id="rbDOYesNo2" name="rbDOYesNo2" type="radio"
class="USDO4 radiobuttonfield" title="Yes Reportable"
value="Yes" onclick="javascript:USDeviceLabeling30Days();"/>
<label for="rbDOYesNo2" class="rptColor">Yes -
Reportable</label>
<input id="rbDOYesNo2" name="rbDOYesNo2" type="radio"
class="USDO5 radiobuttonfield" title="No" value="No"
onclick="javascript:USDeviceLabeling30Days();"/>No - No Report
<div id="calc2" class="indentListCalc">
<input id="dt30Days2" type="text" class="textfieldCalc
labelWidth25" alt="Device Labeling" />
<p></p>
</div>
</li>
</ol>
</div>
</div> <!-- final section Death Occurred end -->
Javascript Code:
function USAYesNoCheckDO() {
if (document.getElementById('rbDeathOccurred').checked) {
document.getElementById('USADOYesNo').style.display = 'block';
} else {
document.getElementById('USADOYesNo').style.display = 'none';
document.getElementsByClassName('USDO')[0].checked = false;
document.getElementsByClassName('USDO1')[0].checked = false;
document.getElementById('calc').style.display = 'none';
document.getElementsByClassName('USDO2')[0].checked = false;
document.getElementsByClassName('USDO3')[0].checked = false;
document.getElementById('calc1').style.display = 'none';
document.getElementsByClassName('USDO4')[0].checked = false;
document.getElementsByClassName('USDO5')[0].checked = false;
document.getElementById('calc2').style.display = 'none';
}
}
I am still learning about all of this HTML, Javascript, and I am just getting into JQuery.
If you need me to put these codes in jsfiddle, please let me know.
Thank you so much,
IreneS
Update:
I forgot to add that the codes work on the server when you select the buttons and the show and hide - the one thing does not work is the clearing the selected buttons.
Thank you again.
Update 2:
After many hours of research and trying to learn Jquery, hoping that it will give me another way to get this issue resolved and get it to work on the server, unfortunately it did not. The reason I was trying Jquery, because I was looking at the other forms that were on the MasterControl server, and they were coded with Jquery. Unfortunately, being a beginner in Jquery, I am not able to get it to work on both sides - the local drive and the server. Please can someone check it and see what I am missing or doing wrong.
function getChecked(radioGroupName, index)
{
var oRadioList = document.getElementsByName(radioGroupName);
return oRadioList[index].checked;
}
function setChecked(radioGroupName, index, state)
{
var oRadioList = document.getElementsByName(radioGroupName);
oRadioList[index].checked = state;
}
function USAYesNoCheckDO()
{
if(getChecked("rbDeathOccured",0) == true)
{
$('#USADOYesNo').slideDown(1000);
}
else
{
$('#USADOYesNo').slideUp(1000);
setChecked("rbDOYesNo",0,false);
setChecked("rbDOYesNo",1,false);
setChecked("rbDOYesNo1",0,false);
setChecked("rbDOYesNo1",1,false);
setChecked("rbDOYesNo2",0,false);
setChecked("rbDOYesNo2",1,false);
}
}
Or if you have any idea how to get this issue fixed. As I mentioned before the buttons work and the show and hide of the questions work, the issue is when I want to reset and set it back to the original status - blank.
Thank you again and appreciate any help.
IreneS
Update 3:
Please anybody have any thoughts/ideas on how to fix this issue.
I really appreciate any help.
Thank you,
IreneS
Update 4:
Just incase someone have the same issue as I am and need a solution, I finally found a website after all this time of searching that gave me the answer and it works! Yeh! I just customized the coding to my needs and it works locally and on the server.
http://www.electrictoolbox.com/javascript-clear-form/
IreneS.
You use the same id attribute for multiple elements. id should be unique on the page, only name can be the same to group multiple input elements of the same type. I don't know if this is the main problem but it is a start.

Condtionally disable button by Radio and Checkbox

I would like to conditionally disable a button based on a radio and checkbox combination. The radio will have two options, the first is checked by default. If the user selects the second option then I would like to disable a button until at least one checkbox has been checked.
I have searched at length on CodePen and Stack Overflow but cannot find a solution that works with my conditionals. The results I did find were close but I couldn't adapt them to my needs as I am a Javascript novice.
I am using JQuery, if that helps.
If needed:
http://codepen.io/traceofwind/pen/EVNxZj
<form>
<div id="input-option1">First option: (required)
<input type="radio" name="required" id="required" value="1" checked="checked">Yes
<input type="radio" name="required" id="required" value="2">No
<div>
<div id="input-option2">Optionals:
<input type="checkbox" name="optionals" id="optionals" value="2a">Optional 1
<input type="checkbox" name="optionals" id="optionals" value="2b">Optional 2
<div>
<div id="input-option3">Extras:
<input type="checkbox" name="extra" id="extra" value="3">Extra 1
<div>
<button type="button" id="btn">Add to Cart</button>
</form>
(Please excuse the code, it is in short hand for example!)
The form element IDs are somewhat fixed. The IDs are generated by OpenCart so I believe the naming convention is set by group, rather than unique. I cannot use IDs such as radio_ID_1 and radio_ID_2, for example; this is an OpenCart framework facet and not a personal choice.
Finally, in pseudo code I am hoping someone can suggest a JQuery / javascript solution along the lines of:
if radio = '2' then
if checkboxes = unchecked then
btn = disabled
else
btn = enabled
end if
end if
Here is a quick solution and I hope that's what you were after.
$(function() {
var $form = $("#form1");
var $btn = $form.find("#btn");
var $radios = $form.find(":radio");
var $checks = $form.find(":checkbox[name='optionals']");
$radios.add($checks).on("change", function() {
var radioVal = $radios.filter(":checked").val();
$btn.prop("disabled", true);
if (radioVal == 2) {
$btn.prop("disabled", !$checks.filter(":checked").length >= 1);
} else {
$btn.prop("disabled", !radioVal);
}
});
});
Here is a demo with the above + your HTML.
Note: Remove all the IDs except the form ID, button ID (since they're used in the demo) as you can't have duplicate IDs in an HTML document. an ID is meant to identify a unique piece of content. If the idea is to style those elements, then use classes.
If you foresee a lot of JavaScript development in your future, then I would highly recommend the JavaScript courses made available by Udacity. Although the full course content is only available for a fee, the most important part of the course materials--the videos and integrated questions--are free.
However, if you don't plan to do a lot of JavaScript development in the future and just need a quick solution so you can move on, here's how to accomplish what you are trying to accomplish:
$(document).ready(function(){
$('form').on('click', 'input[type="radio"]', function(){
conditionallyToggleButton();
});
$('form').on('click', 'input[type="checkbox"]', function(){
conditionallyToggleButton();
});
});
function conditionallyToggleButton()
{
if (shouldDisableButton())
{
disableButton();
}
else
{
enableButton();
}
}
function shouldDisableButton()
{
if ($('div#input-option1 input:checked').val() == 2
&& !$('form input[type="checkbox"]:checked').length)
{
return true;
}
return false;
}
function disableButton()
{
$('button').prop('disabled', true);
}
function enableButton()
{
$('button').prop('disabled', false);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div id="input-option1">First option: (required)
<input type="radio" name="required" id="required" value="1" checked="checked">Yes
<input type="radio" name="required" id="required" value="2">No
<div>
<div id="input-option2">Optionals:
<input type="checkbox" name="optionals" id="optionals" value="2a">Optional 1
<input type="checkbox" name="optionals" id="optionals" value="2b">Optional 2
<div>
<div id="input-option3">Extras:
<input type="checkbox" name="extra" id="extra" value="3">Extra 1
<div>
<button type="button" id="btn">Add to Cart</button>
</form>
Note that the JavaScript code above is a quick-and-dirty solution. To do it right, you would probably want to create a JavaScript class representing the add to cart form that manages the behavior of the form elements and which caches the jQuery-wrapped form elements in properties.

Show Field if Radio Button is Selected

I'm attempting to get the Website URL field on this page to display only when the previous question has the radio button "Yes" selected. I've searched and tried a few code examples, but they aren't working. Does anyone have any suggestions for me?
Thanks in advance!
<div class="editfield">
<div class="radio">
<span class="label">Do you have your own website? (required)</span>
<div id="field_8"><label><input type="radio" name="field_8" id="option_9" value="Yes"> Yes</label><label><input type="radio" name="field_8" id="option_10" value="No"> No</label></div>
</div>
</div>
<div class="editfield">
<label for="field_19">Website URL </label>
<input type="text" name="field_19" id="field_19" value="" />
</div>
I noticed that you initally put the javascript I gave you at the top of the page. If you are going to do this then you need to encapsulate the code in a jquery $(document).ready(function(){ });. You only need to use a document ready when your html follows after the javascript.
$(function() {
// place code here
});
However, in this scenario I have created another alternative that will be better, but do not forget that you have to initially set the web url div as hidden. Also, I highly recommend that you set better control ids; it will make your javascript easier to understand.
$('input[name=field_8]').on("click", function(){
var $div_WebUrl = $('#field_19').closest('.editfield');
if($('input[name=field_8]').index(this) == 0)
$div_WebUrl.show();
else
$div_WebUrl.hide();
});​
Live DEMO
I have created a little example:
<div class="editfield">
<div class="radio">
<span class="label">Do you have your own website? (required)</span>
<div id="field_8"><label><input type="radio" name="field_8" id="option_9" value="Yes" onclick="document.getElementById('divUrl').style.display='block'"> Yes</label><label><input type="radio" name="field_8" id="option_10" value="No" onclick="document.getElementById('divUrl').style.display='none'"> No</label></div>
</div>
</div>
<div class="editfield" id="divUrl" style="display:none">
<label for="field_19">Website URL </label>
<input type="text" name="field_19" id="field_19" value="" />
</div>​
jsFiddle: http://jsfiddle.net/EQkzE/
Note: I have updated the div to include a style, cause I do not know what your css class looks like. Good luck.
Here's a pure JS Solution:
document.getElementById("field_19").parentNode.style.display = "none";
document.getElementById("option_9").onclick = toggleURLInput;
document.getElementById("option_10").onclick = toggleURLInput;
function toggleURLInput(){
document.getElementById("field_19").parentNode.style.display = (document.getElementById("option_9").checked)? "block" : "none";
}
Not a very dynamic solution, but it works.
Something like this will bind the click event to a simple function to look at the radio button and show the other div.
$('#option_9').on('click', function() {
if ($('#option_9').is(':checked')) {
$('#field_19').closest('.editfield').show();
} else {
$('#field_19').closest('.editfield').hide();
}
});
Run sample code

Categories