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().
Related
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.
I have a test input form where a child select box is created depending on the value of one of the choices in the parent select box. Selecting any of the other choices in the parent select box should remove the child. It works, but only once. If the child select box is created a second time, then it is not removed by selecting one of the other choices.
Here is the code:
<html>
<SCRIPT LANGUAGE="JavaScript">
function createtext(){
var var1 = document.getElementById('s');
var var2=var1.value;
if (var2 == "American Express")
{
var selector = document.createElement('select');
selector.id = 'gift';
selector.name = 'gift';
selector.size = '2';
myform.appendChild(selector);
var option = document.createElement('option');
option.value = '0';
option.appendChild(document.createTextNode('Gift card'));
selector.appendChild(option);
option = document.createElement('option');
option.value = '1';
option.appendChild(document.createTextNode('Fully owned card'));
selector.appendChild(option);
}
else
{
myform.removeChild(gift);
}
}
</SCRIPT>
</HEAD>
<BODY >
<form action="" method="get" name="myform">
<SELECT id = "s" name="s" size=3 onChange="createtext()" ><OPTION>Visa Card<OPTION>Mastercard<OPTION>American Express</SELECT>
</form>
</html>
And here it is in action... http://www.crazyforstamps.com/test-form-6.htm
Try
var gel = document.getElementById('gift');
if(gel){
myform.removeChild(gel);
}
Update:
<!DOCTYPE html>
<html>
<head>
<script>
function createtext() {
var var1 = document.getElementById('s');
var var2 = var1.value;
if (var2 == "American Express") {
var selector = document.createElement('select');
selector.id = 'gift';
selector.name = 'gift';
selector.size = '2';
myform.appendChild(selector);
var option = document.createElement('option');
option.value = '0';
option.appendChild(document.createTextNode('Gift card'));
selector.appendChild(option);
option = document.createElement('option');
option.value = '1';
option.appendChild(document.createTextNode('Fully owned card'));
selector.appendChild(option);
} else {
<!--myform.removeChild(gift);
var gel = document.getElementById('gift');
if (gel) {
myform.removeChild(gel);
}
}
}
</script>
</head>
<body>
<form action="" method="get" name="myform">
<SELECT id="s" name="s" size=3 onChange="createtext()">
<OPTION>Visa Card</OPTION>
<OPTION>Mastercard</OPTION>
<OPTION>American Express</OPTION>
</SELECT>
</form>
</body>
</html>
Demo: Plunker
Assuming you have defined gift somewhere which I don't see it in the question.
Removing all child elements
var gift = document.getElementById("gift");
while (gift.firstChild) {
gift.removeChild(gift.firstChild);
}
Or another alternative is to simply assign innerHTML to an empty string
var gift = document.getElementById("gift");
gift.innerHTML = '';
First of all you have to keep in mind, that each browser has it's own js compiler. Some can use properties without getting browsers dom element via JS, by just referencing their name. But in order to write all browsers supported code, you have to keep in mind JS specifications.
In your current example on JSFiddle you have to always get your elements before you try to perform any actions on them.
var myform = document.getElementById('myform');
var gift = document.getElementById('gift');
I have a Search Filter for Check box List using Jquery and java Script....Also i have Checkall and UncheckAll radio buttons..If i enable CheckAll button...it will check all checkboxes in that list...If i filter the list using search filter, also it will check all checkboxes in that list...
Now i want to check only filtered items in the list should checked, if i click checkall....
If i not filter means it will check all items in the list...
My codings are below...
CheckAll coding:
<script>
function checkall(formname,checkname,thestate)
{
var el_collection=eval("document.forms."+formname+"."+checkname);
for (c=0;c<el_collection.length;c++)
el_collection[c].checked=thestate
}
</script>
Search Filter Coding:
<script>
(function ($) {
jQuery.expr[':'].Contains = function(a,i,m){
return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
};
function listFilter(header, list) {
var form = $("<form>").attr({"class":"filterform","action":"#"}),
input = $("<input>").attr({"class":"filterinput","type":"text"});
$(form).append(input).appendTo(header);
$(input)
.change( function () {
var filter = $(this).val();
if(filter) {
$(list).find("a:not(:Contains(" + filter + "))").parent().slideUp();
$(list).find("a:Contains(" + filter + ")").parent().slideDown();
} else {
$(list).find("li").slideDown();
}
return false;
})
.keyup( function () {
$(this).change();
});
}
$(function () {
listFilter($("#header"), $("#list"));
listFilter($("#header1"), $("#list1"));
});
}(jQuery));
</script>
<script type="text/javascript">
function show()
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","location.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("value");
for (i=0;i<x.length;i++)
{
var name=x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
var link = document.createElement( "a" );
var list = document.createElement( "li" );
var cb = document.createElement( "input" );
cb.type = "checkbox";
cb.id = "c1";
cb.value = name;
cb.name="v1";
cb.checked = false;
link.appendChild(cb);
link.innerHTML+=name;
var lists=document.getElementById('list');
list.appendChild(link);
lists.appendChild(list);
}
}
</script>
My body Tag codings:
<form id="tracklocation">
<ul id="list" style="list-style:none">
</ul>
<h1 id="header1">DVD Collection</h1>
<input type="radio" value="ca" name="dt" onclick="checkall('tracklocation','v1',true)">Check All <input type="radio" value="ua" name="dt" onclick="checkall('tracklocation','v1',false)">Uncheck All
</form>
How to checkall only filtered items in the list..please help me....
This doesn't answer your question but it's much better formatted as an answer than a comment.
Please don't use eval where square bracket notation is by far the better option. Where you have:
> var el_collection=eval("document.forms."+formname+"."+checkname);
presuming that checkname is the name of a radio button set, then it should be:
var el_collection = document.forms[formname][checkname];
Note also that if there is only one such input, el_collection will be a reference to that element and not an HTMLCollection, so you should check for that.
Change checkall function like this using Jquery...it will work fine....
function checkall(formname,checkname,thestate)
{
if ($('li').is(':hidden')) {
var visible = $('input[type=checkbox]:visible').each(function() {
this.checked = thestate; }
);
}
else
{
var visible = $('input[type=checkbox]').each(function() {
this.checked = thestate; }
);
}
}
I would like help to manipulate to following javascript code so that there are buttons instead of the first drop-down-menu have buttons to choose the values of the next set of values for the drop-down-menus.
The code is:
<html>
<head><title>JS example</title></head>
<body>
<script type="text/javascript"><!--
//
var opt_one = new Array('blue', 'green', 'red');
var opt_two = new Array('plaid', 'paisley', 'stripes');
//
function updateTarget() {
var f = document.myform;
var which_r = null;
if (f) {
// first option selected? ("One")
if (f.trigger.value == '1') {
which_r = opt_one;
// ...or, second option selected? ("Two")
} else if (f.trigger.value == '2') {
which_r = opt_two;
// no known option, hide the secondary popup
} else {
f.target.style.display = 'none';
}
// did we find secondary options for the selection?
if (which_r) {
// reset/clear the target pop-up
f.target.innerHTML = '';
// add each option
for (var opt in which_r) {
f.target.innerHTML += '<option>' + which_r[opt] + '</option>';
}
// display the secondary pop-up
f.target.style.display = 'inline';
}
}
} // updateTarget()
//-->
</script>
<form name="myform" action="#">
<select name="trigger" onchange="updateTarget();">
<option>Select one...</option>
<option>-</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
<select name="target" style="display:none;">
</select>
</form>
</body>
</html>
So what I am trying to do is make it that the words 'ONE' and 'TWO' instead of being in a drop-down-menu, be buttons. So that when it is cliked it brings up their specified array.
Thank you in advance!
If I understand your question correctly this should work.
<html>
<head><title>JS example</title></head>
<body>
<script type="text/javascript"><!--
//
var opt_one = new Array('blue', 'green', 'red');
var opt_two = new Array('plaid', 'paisley', 'stripes');
//
function updateTarget(button) {
var f = document.myform;
var which_r = null;
if (f) {
// first option selected? ("One")
if (button.name == 'one') {
which_r = opt_one;
// ...or, second option selected? ("Two")
} else if (button.name == 'two') {
which_r = opt_two;
// no known option, hide the secondary popup
} else {
f.target.style.display = 'none';
}
// did we find secondary options for the selection?
if (which_r) {
// reset/clear the target pop-up
f.target.innerHTML = '';
// add each option
for (var opt in which_r) {
f.target.innerHTML += '<option>' + which_r[opt] + '</option>';
}
// display the secondary pop-up
f.target.style.display = 'inline';
}
}
} // updateTarget()
//-->
</script>
<form name="myform" action="#">
<input name="one" type="button" onclick="updateTarget(this)" value="One"/> <input name="two" type="button" onclick="updateTarget(this)" value="Two"/>
<select name="target" style="display:none;">
</select>
</form>
</body>
</html>
You could simply create two buttons and invoke the updateTarget() function in the onClick event of the buttons :
<input type="button" value="Option 1" onclick="updateTarget(1);" />
<input type="button" value="Option 2" onclick="updateTarget(2);" />
Note that the signature of the updateTarget() must change to allow you to pass the parameter so that your code can branch accordingly:
function updateTarget(optionNumber)
{
if (optionNumber == 1)
...
else if (optionNumber == 2)
...
else
...
}
How can i change the field size diynamicaly?
I have a select field and there are 3 options with different values.
So if the user selects one of them in the you see the values.
But how can i change the size that the values from option field fits in the
function changeText()
{
var select = document.getElementById("surl");
var textfield = document.getElementById("turl");
var bold = document.getElementById("burl");
var link = document.getElementById("linkText");
if(bold.style.display == "none")
bold.style.display = "";
//if(link.innerHtml)
bold.innerHtml = select.value;
//if(link.innerHTML !="")
link.innerHTML= select.value;
textfield.value = select.value;
}
<b>Sample: </b><select id="surl" onchange="changeText();" style="visibility: visible;" name="linkText">
<option>Select LinkText</option>
<option value="<a href='http://www.doesntexist.dsdsd/'>Want sign? http://www.doesntexist.dsdsd</a>">
Variant1
</option>
<option value="<a href='http://www.doesntexist.dsdsd/'>Wanna killme? http://www.doesntexist.dsdsd</a>">
Variant 2
</option>
</select>
<br />
<div class="succes">
<span id="burl" style="display: none"><br /><a id="linkText" href="http://www.doesntexist/"></a></span>
</div>
</p>
<p>
<textarea id="turl" style="">
text...
</textarea>
</p>
Sorry, I must’ve misunderstood your problem.
So you want to resize a textarea dynamically based on what, its contents? You could use the jQuery autoResize plugin for this…
A quick 'n' dirty jQuery solution would be the following:
$('input#foo-option-1').bind('change, click', function() {
if ($(this).is(':checked')) {
$('textarea').css('height', '150px');
}
});
$('input#foo-option-2').bind('change, click', function() {
if ($(this).is(':checked')) {
$('textarea').css('height', '250px');
}
});
$('input#foo-option-3').bind('change, click', function() {
if ($(this).is(':checked')) {
$('textarea').css('height', '350px');
}
});
Of course, this code isn’t very DRY. Moreover, modifying CSS properties through JavaScript is never a very good idea — it’s better to add classes dynamically through JS and specify the actual CSS in your CSS files (duh).
For example:
<script type="text/javascript">
document.getElementById("textarea_id").style.width = "300px";
document.getElementById("textarea_id").style.width = "200px";
</script>
First of all i thought there are more devs who can help; any way here is the answer
first create a function which calculates the strlen
function strlen(strVar)
{
return(strVar.length)
}
Second create a var tfcount
var tfcount = strlen(select.value);
and finaly
textfield.style.width = tfcount < 110 ? tfcount = 110 : 3.5*tfcount+"px";
textfield.style.height = tfcount < 110 ? tfcount = 110 : tfcount/2.5+"px";