Switch a button depending on check box selection - javascript

I currently am building a form that has 3 checkboxes and a dynamic button that appears below.
My current issue is when you select more than one then tick off one more both the active state and deactivate state buttons appear
https://staging-homecarepulse.kinsta.cloud/demo-select/ here is my demo link
Here is the script im using
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>$(document).on("change", ".mod-link", function() {
var arr = []
$(".mod-link:checked").each(function() {
arr.push($(this).val());
})
if ($(this).is(":checked")) {
$('#picture').attr('src', '');
} else {
$('#picture').attr('src', 'https://staging-homecarepulse.kinsta.cloud/wp-content/uploads/2021/06/greyBTN.jpg');
}
var vals = arr.join(",")
var str = "/demo/?demo_request_type=" + vals;
var link = arr.length > 0 ? '<a class="dynabtn" href="'+str+'">Continue</a>': '' ;
$('.link-container').html(link);
});
</script>
here is my html
<input type="checkbox" id="checkbox1" class="mod-link" name="selected" value="es" hidden>
<label for="checkbox1" style="cursor: pointer;">CHECK BOX styling and info HERE</label>
<div class="link-container" style="text-align:center;"></div>
<div style="text-align:center;">
<span class="result_img">
<img id="picture" src="https://staging-homecarepulse.kinsta.cloud/wp-content/uploads/2021/06/greyBTN.jpg"/>
</span>
</div>
I would like to figure out how to hide the grey image button until ALL OR NO checkboxes are selected. so for short #picture should not display until ALL OR NO CHECKBOXES ARE SELECTED
Any help is appreciated

You can check arr.length earlier for showing and hiding gray button as well. Please see below code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>$(document).on("change", ".mod-link", function() {
var arr = []
$(".mod-link:checked").each(function() {
arr.push($(this).val());
})
if (arr.length > 0) {
$('#picture').attr('src', '');
} else {
$('#picture').attr('src', 'https://staging-homecarepulse.kinsta.cloud/wp-content/uploads/2021/06/greyBTN.jpg');
}
var vals = arr.join(",")
var str = "/demo/?demo_request_type=" + vals;
var link = arr.length > 0 ? '<a class="dynabtn" href="'+str+'">Continue</a>': '' ;
$('.link-container').html(link);
});
</script>
Hope it resolve your issue.

Related

How to connect JS functions to checkbox

Hello,
I am making a simple text changer website where I want the user to be able to select what options to use. Right now I have two options; myConvertOption which capitalizes every odd letter in a word and I have myScrambleOption which randomly mixes up each word a bit.
Right now whenever you click on Caps (checkbox_1) it already executes the function where I only want it to execute whenever the user clicks on the "Convert" button + it also puts spaces in between each letter now.
The Scramble button (checkbox_2) doesn't do anything for some reason, except for console logging the change.
JSfiddle: https://jsfiddle.net/MysteriousDuck/hLjytr2p/1/
Any help and suggestions will be greatly appreciated!
P.S I am new to Javascript.
Checkbox event listeners:
checkbox_1.addEventListener('change', function () {
console.log("checkbox_1 changed");
if (this.checked) {
myConvertFunction();
} else {
//Do nothing
}
})
checkbox_2.addEventListener('change', function () {
console.log("checkbox_2 changed");
if (this.checked) {
myScrambleFunction(text);
} else {
//Do nothing
}
})
Checkbox HTML:
<div class="checkbox">
<input type="checkbox" id="checkbox_1" >
<label for="checkbox_1">Caps</label>
</div>
<div class="checkbox">
<input type="checkbox" id="checkbox_2" >
<label for="checkbox_2">Scramble</label>
</div>
this works properly..
You just had to add the event on the button and then test which check box was checked, and other little things
<!doctype html>
<html>
<head>
</head>
<body>
<div class="container">
<h1> Text Changer </h1>
<h2> CAPS + randomize letters text changer</h2>
<div class="checkbox">
<input type="checkbox" id="checkbox_1">
<label for="checkbox_1">Caps</label>
</div>
<div class="checkbox">
<input type="checkbox" id="checkbox_2">
<label for="checkbox_2">Scramble</label>
</div>
<textarea type="text" autofocus="true" placeholder="input text" id="inputText" value="Input Value" spellcheck="false" style="width: 300px;"></textarea>
<button class="button button1" id="convertText">Convert</button>
<textarea type="text" placeholder="converted text" id="convertedText" value="Clear" readonly="true" spellcheck="false" style="width: 300px;"></textarea>
<button class="button button1" id="copyText">Copy</button>
</div>
<script>
var text = document.getElementById("inputText").value;
var convertText = document.getElementById("convertText");
var checkbox_2 = document.getElementById("checkbox_2");
var checkbox_1 = document.getElementById("checkbox_1");
//Capitalize every odd letter
function myConvertFunction() {
var x = document.getElementById("inputText").value;
var string = "";
for (let i = 0; i < x.length; i++) {
if (i % 2 == 0) {
string = string + x[i].toUpperCase();
} else {
string = string + x[i];;
}
}
return string;
}
//Scramble words
function myScrambleFunction(text) {
let words = text.split(" ");
words = words.map(word => {
if (word.length >= 3) {
return word.split('').sort(() => 0.7 - Math.random()).join('');
}
return word;
});
return words.join(' ');
}
document.getElementById("copyText").addEventListener("click", myCopyFunction);
//Copy textarea output
function myCopyFunction() {
var copyText = document.getElementById("convertedText");
copyText.select();
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
eraseText();
}
//Delete textarea output
function eraseText() {
document.getElementById("convertedText").value = "";
document.getElementById("inputText").value = "";
document.getElementById("inputText").focus();
}
//don't add the event to the radio buttons (previously checkboxes), add it to the convert button, and in its function test which radio button has been checked
convertText.addEventListener('click', function() {
if (checkbox_1.checked && checkbox_2.checked) {
console.log("doing both options");
document.getElementById("convertedText").value = myScrambleFunction(myConvertFunction());
} else if (checkbox_2.checked) {
console.log("proceeding scrumble");
document.getElementById("convertedText").value = myScrambleFunction(text);
} else if (checkbox_1.checked) {
console.log("proceeding cap");
document.getElementById("convertedText").value = myConvertFunction();
}
})
</script>
</body>
</html>
You're never updating var text.
You need to update it before using it if you want the value to be something other than an empty string.
checkbox_2.addEventListener('change', function () {
console.log("checkbox_2 changed");
if (this.checked) {
text = document.getElementById("inputText").value;
myScrambleFunction(text);
} else {
//Do nothing
}

add up values from siblings using jQuery

Hi Guys I have been working on this script for some time and I just cant make it work well I may be missing an important argument to get it to work properly..
I need to calculate the values from inside of a tag and add up the total to a heres the HTML:
<div class="catProdAttributeItem">
<input type="radio" id="5583116" name="752526">
<span>Ford £19.99</span>
<img src="http://www.breakerlink.com/blog/wp-content/uploads/2014/01/Ford.png">
</div>
<div class="catProdAttributeItem">
<input type="radio" id="5971554" name="752526">
<span>Ferrary £19.99</span>
<img src="http://www.assettocorsa.net/wp-content/uploads/2013/09/logo2.png">
</div>
<br><br>
<span style="display:none;" class="original_price">£0.00</span>
<div class="updated_price" id="show-price">£0.00</div>
And here is my Script:
$('.catProdAttributeItem img').on("click", function() {
$(this).siblings('input[type=radio]').attr('checked', true);
var original_price = $('.original_price').text().replace(/[^0-9\.]/g, '');
parseFloat(this.original_price);
var warehouse_price = $(this).siblings('.catProdAttributeItem span').text().replace(/[^0-9\.]/g, '');
warehouse_price = parseFloat(warehouse_price);
var total_price = parseFloat(original_price) + parseFloat(warehouse_price);
$('.updated_price').html('£' + total_price.toFixed(2));
})
I can only get the result of the clicked siblings, please some help is much appreciated..
I was expecting to add up the values displayed on the .updated_price when the input is selected but it will work on a wider set of inputs where you can check more inputs and you would get the result from all the inputs checked
DEMO FIDDLE
You need the checkbox for each car (not radio). See below:
$(document).ready(function() {
$('.catProdAttributeItem img').on("click", function() {
// Make checkbox adjustment
$(this).siblings('input:checkbox').click();
});
$(document).on('click', 'input:checkbox', calcTotal);
});
function calcTotal() {
var total_price = 0;
// find all .catProdAttributeItem divs
$(document).find('.catProdAttributeItem').each(function() {
// see if the checkbox is checked to add to the total_price
var $checkbox = $(this).find('input:checkbox');
if ($checkbox.is(':checked')) {
var text = $(this).find('span').html();
total_price += parseFloat(text.replace(/[^0-9\.]/g, ''))
}
});
// finally display the price
$('.updated_price').html('£' + total_price.toFixed(2));
}
.catProdAttributeItem {
width: 300px;
float: left;
display: inline-block;
text-align: center;
}
img {
width: 100px;
height: auto;
}
.updated_price {
clear: both;
margin: 20px 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="catProdAttributeItem">
<input type="checkbox" id="5583116" name="752526">
<span>Ford £19.99</span>
<img src="http://www.breakerlink.com/blog/wp-content/uploads/2014/01/Ford.png">
</div>
<div class="catProdAttributeItem">
<input type="checkbox" id="5971554" name="752526">
<span>Ferrary £19.99</span>
<img src="http://www.assettocorsa.net/wp-content/uploads/2013/09/logo2.png">
</div>
<br>
<br>
<div class="updated_price" id="show-price">£0.00</div>
From my understanding of what you're trying to do, you will want to simply iterate over all .catProdAttributeItem elements and add the price only if the radio button is checked:
var warehouse_price = 0;
$('.catProdAttributeItem')
.filter(function() {
// only interested in checked radio boxes
return $('input:checked', this).length > 0;
})
.each(function() {
var price = parseFloat($('span', this).text().replace(/[^\d.]/, ''));
warehouse_price += price;
});
$('.updated_price').html('£' + total_price.toFixed(2));
This answer is a combination of Sigismundus answer + A bit of twicks to be able to grab the results from both either the radio buttons and check boxes the img click didn't work quite well, but now if added a new function to get the images as radio buttons it would work.
var priceSelect = parseFloat(document.getElementById("totalprice").value);
$('.catProdAttributeItem input[type=radio], .catProdAttributeItem input[type=checkbox] ').on("click", function() {
var total_price = 0;
$(document).find('.catProdAttributeItem').each(function() {
var $checkbox = $(this).find('input:radio, input:checkbox');
if ($checkbox.is(':checked')) {
var text = $(this).find('span').html();
total_price += parseFloat(text.replace(/[^0-9\.]/g, ''))
}
});
$('#totalprice').html('£' + total_price.toFixed(2));
document.getElementById('totalprice').value = total_price+priceSelect;
});

Search through list items on every input key press using jQuery and hide other item

I have code of list item , I want to search items using textbox how i can perform:-
Pricerange.Append("<ul>");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Pricerange.Append(
"<li><span class='pull-left'><a href='default.aspx?Price=" +
ds.Tables[0].Rows[i]["Max_id"] + "' >" + ds.Tables[0].Rows[i]["Max_Price"] +
"</a></span> <span class='counter-pro pull-right'>12</span></li>");
}
Pricerange.Append("</ul>");
divpricerange.InnerHtml = Pricerange.ToString();
See This Image
- on left hand side in refine search i want to perform autocomplete action and hide other listitem.
You could use jQuery :contains selector to search the list and then show/hide list items based on the search result.
Here is a quick snippet that would give you an idea:
Demo Fiddle: http://jsfiddle.net/mwdune35/1/
/* jQuery code to search and reveal */
$("#txt").on("keyup", function() {
var srchTerm = $(this).val(),
$rows = $("#lst").children("li");
if (srchTerm.length > 0) {
$rows.stop().hide();
$("#lst").find("li:contains('" + srchTerm + "')").stop().show();
} else {
$rows.stop().show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Your HTML -->
<input id="txt" type="text" />
<br />
<ul id="lst">
<li>JM Aroma</li>
<li>Red Square Bonanza</li>
<li>Skylabs Special</li>
<li>Society Someplace</li>
<li>Anywhere</li>
<li>Everywhere</li>
<li>Nowhere</li>
<li>Somewhere</li>
</ul>
Kindly check this post
It uses Tables instead of list, but you can play with it.
$.each($("#table tbody").find("tr"), function() {
if($(this).text().toLowerCase().indexOf($(_this).val().toLowerCase()) == -1)
$(this).hide();
else
$(this).show();
})
In this way this script will executed thanks # abhitalks for valuable suggestion..
$(document).ready(function () {
$("#txt").on("keyup", function () {
var srchTerm = $(this).val(),
$rows = $("#lst").children("li");
if (srchTerm.length > 0) {
$rows.stop().hide();
$("#lst").find("li:contains('" + srchTerm + "')").stop().show();
} else {
$rows.stop().show();
}
});
});

"search" field to filter content

I'm trying to create a simple "search field", what it does is it searches if typed in text is equal to any data-attr of the boxes in the content and if so, hide everything but what found, something similar (this ain't working):
css:
.filter-div {
display: none;
}
html:
<label for="search">Search Input:</label>
<input type="search" name="filter" id="search" value="" />
<div class="filter-div" data-filter="one">one</div>
<div class="filter-div" data-filter="two">two</div>
<div class="filter-div" data-filter="three">three</div>
<div class="filter-div" data-filter="four">four</div>
<div class="filter-div" data-filter="five">five</div>
jquery:
// save the default value on page load
var filter = $('.input').val();
// on submit, compare
if ( $('.input').val() = $("data-filter") {
$(this).show();
} ​
I am also not sure if the content should be filtered with a button click or found content should pop up as click-able text in the search, or should all happen auto? Finally probably I will have to check it against more than one data-attr.
Anyone?
$('#search').on('keyup', function() {
var val = $.trim(this.value);
if (val) {
$('div[data-filter=' + val + ']').show();
} else $('div[data-filter]').hide();
});
Working sample
According to demo fiddle example in comment
var divs = $('div[data-filter]');
$('#search').on('keyup', function() {
var val = $.trim(this.value);
divs.hide();
divs.filter(function() {
return $(this).data('filter').search(val) >= 0
}).show();
});
divs.on('click', function() {
divs.not(this).hide();
var text = $.trim($(this).text());
$('#search').val(text);
});
Working sample
JavaScript:
var filter_div = $('[data-filter]');
$('#search').keyup(function(){
var val = $.trim(this.value);
filter_div.hide();
if(val.length == 0) return;
filter_div.filter(function(){
return $(this).data('filter').indexOf(val)>-1
}).show();
});
Fiddle: http://jsfiddle.net/iambriansreed/xMwS5/
​

How to remove a selected option from html select?

My actual question is quite bit complicated compared to its title. I am very new to Javascript and jQuery so please bear with me.
I would suggest that you run this code first before reading my question so you can understand what I'm trying to do.
<html>
<head>
<script type="text/javascript" src="jquery1.6.4min.js"></script>
<script type="text/javascript" >
var selectedAddFootballPlayerId = '';
var selectedAddFootballPlayerName = '';
var selectedRemoveFootballPlayerId = '';
var selectedRemoveFootballPlayerName = '';
$(document).ready(function() {
$('#listboxFootballPlayers option').click(function() {
selectedAddFootballPlayerId = $(this).attr('value');
selectedAddFootballPlayerName = $(this).text();
});
$('#selectedFootballPlayers option').click(function() {
selectedRemoveFootballPlayerId = $(this).attr('value');
selectedRemoveFootballPlayerName = $(this).text();
});
$('input#btnAddFootballPlayerToList').click(function() {
if (selectedAddFootballPlayerId == '') {
alert("Select a football player to be added from the list.");
} else {
var option = new Option(selectedAddFootballPlayerName , selectedAddFootballPlayerId);
$(option).html(selectedAddFootballPlayerName);
$('#selectedFootballPlayers').append(option);
selectedAddFootballPlayerId = '';
selectedAddFootballPlayerName = '';
}
});
$('input#btnRemoveFootballPlayerFromList').click(function() {
if (selectedRemoveFootballPlayerId == '') {
alert("Select a football player to be removed from the list.");
} else {
var option = new Option(selectedRemoveFootballPlayerName , selectedRemoveFootballPlayerId);
$(option).html(selectedRemoveFootballPlayerName);
$('#listboxFootballPlayers').append(option);
selectedRemoveFootballPlayerId = '';
selectedRemoveFootballPlayerName = '';
}
});
});
</script>
</head>
<body>
<table>
<tr>
<td>
<select id="listboxFootballPlayers" size="5" multiple="multiple" style="width: 200px;">
<option value="l1">Cristiano Ronaldo</option>
<option value="l2">Ricardo Kaka</option>
<option value="l3">Lionel Messi</option>
<option value="l4">Gerd Muller</option>
<option value="l5">Johan Crujjf</option>
<option value="l6">Franz Beckenbauer</option>
<option value="l7">David Beckham</option>
</select>
</td>
<td>
<table>
<tr><td><input type="button" id="btnAddFootballPlayerToList" value="->" /> </td></tr>
<tr><td><input type="button" id="btnRemoveFootballPlayerFromList" value="<-" /></td></tr>
</table>
</td>
<td>
<select id="selectedFootballPlayers" size="5" multiple="multiple" style="width: 200px;"></select>
</td>
</tr>
</table>
</body>
</html>
Before I start with the question please take note:
#listboxFootballPlayers - The listbox on the left
#selectedFootballPlayers - The listbox on the right
I have 2 questions:
How can I remove the selected item / option from #listboxFootballPlayers after I clicked on -> button.
Why is it that when I click on <- after I selected an item / option from #selectedFootballPlayers it gives me a message Select a football player to be removed from the list. It seems to me that it doesn't assign the value on the variable selectedRemoveFootballPlayerId.
Please ask me if there are something that are not clear with my question. Please help.
Here is the jsfiddle link: http://jsfiddle.net/7vspM/
$(document).ready(function() {
$('#listboxFootballPlayers option').click(function() {
selectedAddFootballPlayerId = $(this).attr('value');
selectedAddFootballPlayerName = $(this).text();
});
$('#selectedFootballPlayers option').live('click', // `live()` event for `option` bcoz, option in this select will
// create after DOM ready
function() {
selectedRemoveFootballPlayerId = $(this).attr('value');
selectedRemoveFootballPlayerName = $(this).text();
});
$('input#btnAddFootballPlayerToList').click(function() {
if (selectedAddFootballPlayerId == '') {
alert("Select a football player to be added from the list.");
} else {
var option = new Option(selectedAddFootballPlayerName, selectedAddFootballPlayerId);
$(option).html(selectedAddFootballPlayerName);
$('#selectedFootballPlayers').append(option);
$('#listboxFootballPlayers option:selected').remove(); // remove selected option
selectedAddFootballPlayerId = '';
selectedAddFootballPlayerName = '';
}
});
$('input#btnRemoveFootballPlayerFromList').click(function() {
if (selectedRemoveFootballPlayerId == '') {
alert("Select a football player to be removed from the list.");
} else {
var option = new Option(selectedRemoveFootballPlayerName, selectedRemoveFootballPlayerId);
$(option).html(selectedRemoveFootballPlayerName);
$('#selectedFootballPlayers option:selected').remove(); // remove selected option
$('#listboxFootballPlayers').append(option);
selectedRemoveFootballPlayerId = '';
selectedRemoveFootballPlayerName = '';
}
});
});
Regarding 2):
The problem is that you assign the click functionality before you create the element to assign it to. When you create your option you should assign it instead, like this:
$(option).click(function() {
selectedRemoveFootballPlayerId = $(this).attr('value');
selectedRemoveFootballPlayerName = $(this).text();
});
Regarding question one, it's somewhat easier to simply move the selected option element from one list to the other:
$('#listboxFootballPlayers option:selected').appendTo('#selectedFootballPlayers');
I've commented out the lines that don't appear to be needed in the JS Fiddle demo.
As for your second question, I've rewritten the if/else statement:
$('input#btnRemoveFootballPlayerFromList').click(function() {
if (!$('#selectedFootballPlayers option:selected')){
alert("First select a player to remove.");
}
else {
$('#selectedFootballPlayers option:selected').appendTo('#listboxFootballPlayers ');
}
});
JS Fiddle demo.
References:
:selected.
appendTo().

Categories