Cloning Checkboxes with different names - javascript

For better understanding what I want to do, here is a screenshot
I want to be able to submit whether checkboxes are checked or not. For this I used the trick to have hidden input fields, because otherwise unchecked boxes are not submitted. What I want to do now is to give pairs (one hidden, one checkbox) the same name, but each pair a different name. I tried quite a bit with javascript and jQuery but could not figure out how to get this done. The "+" Button is for adding more Checkboxes, the "-" Button is for deleting them again.
<html>
<head>
<title>test</title>
<script type="text/javascript">
function clone(button, objid)
{
tmpvalue = document.test.elements['param[]'][1].value;
document.test.elements['param[]'][1].value = '';
var clone_me = document.getElementById(objid).firstChild.cloneNode(true);
button.parentNode.insertBefore(clone_me, button);
document.test.elements['param[]'][1].value = tmpvalue;
}
function remove_this(objLink)
{
objLink.parentNode.parentNode.parentNode.parentNode.parentNode.removeChild(objLink.parentNode.parentNode.parentNode.parentNode);
}
</script>
</head>
<body>
<form name="test" method="post" action="test2.php">
<input name="param[0]" value="0" type="hidden">
<div id="hidden" style="visibility:hidden; display:none">
<div id="table"><table>
<tr><td>
<input name="param[]" type='hidden' value="0">
Parameter: <input name="param[]" type="checkbox" value="1">
</td>
<td>
<span style="margin-left:2em;"></span><input value="-" onclick="javascript:remove_this(this)" type="button">
</td>
</tr>
</table></div>
</div>
<div>
<input style="margin-top:2em;" value="+" onclick="javascript:clone(this, 'table');" type="button">
<button type="submit" name="sent">Submit</button>
</div>
</form>
</body>
</html>
So it would actually be nice to have some sort of counter like this:
<input name="param[i]" type='hidden' value="0">
Parameter: <input name="param[i]" type="checkbox" value="1">
Thanks for your help!

What about giving your checkboxes a class (for example "checkClass") and then scan all elements with this class using a jQuery? Like so..
// instead of $('button[type="submit"]') give your button an ID and use # selector
$('button[type="submit"]').click(function(){
//lets get all checkboxes..
$('.checkClass').each(function(){
// get their checked status
var checked = $(this).is(':checked');
// ..and do whatever you need here..
});
});
In terms of adding a new row on "plus" button click. Try considering the jquery "Append" method. Like so..
$('#plusButtonId').click(function(){
var rowHtml = '<tr><td>Parameter: <input name="param[]" type="checkbox" class="checkClass" value="1"></td><td><input value="-" type="button" class="remButton"></td></tr>';
$('#table').append(rowHtml);
});
..then use the ".remButton" selector and add a click event that will remove that tr element.
and last but not least - this is a great example why to start with AngularJS. It would be just one controller, a div with "ng-repeat" and a few methods. Try it ;)

Related

copy text into field using radio selection

I am wanting to create the following using CSS, HTML and JavaScript
Course1 //dropdown selection//
....
Course2 //dropdown selection//
.....
WINNER
(RADIO checked for Course1) OR (RADIO clicked for Course2)
//automatically populated from either Course1 or Course2 depending on Radio checked//
but my dropdown selection and radio selection hamper each other.
When I have the name from the radio the same "winnerselected" the radio works, but the copying from the course1 or course2 doesn't work.
Maybe someone has created code like this somewhere else and knows how to get around it?
Any assistance will be appreciate.
code as follows:
<!--Make sure the form has the autocomplete function switched off:-->
<form autocomplete="off" action="/action_page.php">
<div class="autocomplete" style="width:300px;">
Course 1
<input id="myInput" type="text" name="golfcoursename1" placeholder="Golf
Course">
<form autocomplete="off" action="/action_page.php">
<div class="autocomplete" style="width:300px;">
Course 2
<input id="myInput1" type="text" name="golfcoursename2" placeholder="Golf
Course">
</div>
<p>
WINNER
<p>
<input type="radio" id="Course1" name="winnerselected" value="Course1"
onclick="FillWinner(this.form)">
<label for="Course1">Course 1</label>
<input type="radio" id="Course2" name="winnerselected" value="Course2"
onclick="FillWinner2(this.form)">
<label for="Course2">Course 2</label><br>
<input type="text" id="winner" name="Winner" placeholder="Winner">
<p>
</p>
<input type="submit">
</form>
<script>
function FillWinner(f) {
if(f.winnerselected.checked == true) {
f.winner.value = f.golfcoursename1.value;
if(f.winnerselected.checked == true)
f.winner.value = f.golfcoursename2.value;
}}
</script>
First, your HTML is not valid as you have a second form, with no closing tag, nested in the first one. Also, while is is legal to not close a p element, you really should for clarity sake.
Next, remove inline styles and inline JavaScript from your HTML. It just clutters up the code, causes redundancy, and is harder to read and maintain. Instead break your work into HTML, CSS, and JavaScript sections.
It's not clear what you exactly want, but my guess is that whichever radio button is clicked should dictate which textbox value becomes the winner. Based on that, see the comments inline below for a description of how the code works.
.autocomplete { width:300px; }
<!--Make sure the form has the autocomplete function switched off:-->
<form autocomplete="off" action="/action_page.php">
<div class="courses">
<div class="autocomplete">
Course 1 <input id="myInput" name="golfcoursename1" placeholder="Golf Course">
</div>
<div class="autocomplete">
Course 2 <input id="myInput1" name="golfcoursename2" placeholder="Golf Course">
</div>
</div>
<p>WINNER</p>
<p id="radioContainer">
<input type="radio" id="Course1" name="winnerselected" value="Course1">
<label for="Course1">Course 1</label>
<input type="radio" id="Course2" name="winnerselected" value="Course2">
<label for="Course2">Course 2</label><br>
<input type="text" id="winner" name="Winner" placeholder="Winner">
</p>
<input type="submit">
</form>
<script>
// Don't use inline HTML event attributes like onclick.
// Separate your JavaScript from your HTML
// Get references to the element(s) you'll need to work with
// Get all the elements that have a name attribute that starts with "golfcoursename"
const courseNames = document.querySelectorAll("[name^='golfcoursename']");
// Get all the elements that have a name attribute that is exactly "winnerselected"
const radioButtons = document.querySelectorAll("[name='winnerselected']");
const winner = document.getElementById("winner");
// Here's how to set up events in JS
const radCont = document.getElementById("radioContainer").addEventListener("click", fillWinner);
function fillWinner(event) {
// Look at the radiobuttons collection and get the index of the selected radio button from it.
const indexOfTextbox = Array.from(radioButtons).indexOf(event.target);
// Set the value of the winner textbox to textbox with the same index as the clicked radio button
winner.value = courseNames[indexOfTextbox].value;
}
</script>

JavaScript parse button value to post

i have a form that contains different buttons with different values that i want to post to a controller or something equal. Here is how this could look like:
<form action="thecontroller/post" method="post" id="buttons">
<div class="select_direct">
<button class="btn_quick_select" value="A">A</button>
<button class="btn_quick_select" value="B">B</button>
<button class="btn_quick_select" value="C">C</button>
</div>
<button type="submit" name="add">
</form>
So i want to submit the selected button (A, B or C) to the controller. As i want to satisfy the Open-Close-Principle, i want to be able to do this for any amount of buttons given, so my approach ist to parse the elements by class and filter for the active one:
var buttonValue;
function getSelectedButton() {
var buttons = document.getElementsByClassName("select_direct");
buttons.foreach(function(button) {
if(button.isActive) { buttonValue = button.value; }
});
}
Is there a better way to achieve this?
So i want to submit the selected button (A, B or C) to the controller.
Sounds like you're re-inventing a radio button.
const form = document.getElementById("buttons");
form.addEventListener("submit", (e)=>{
e.preventDefault();
console.log(document.querySelector('input[name="letter"]:checked').value);
});
<form action="thecontroller/post" method="post" id="buttons">
<div class="select_direct">
A<input type="radio" value="A" name="letter" />
B<input type="radio" value="B" name="letter" />
C<input type="radio" value="C" name="letter" />
</div>
<input type="submit" name="add">
</form>
No need for JavaScript.
If you want to first click on A/B/C and then the submit button, then don't use normal buttons for A/B/C, but radio buttons and use CSS to make them look like normal buttons.
If you want to just click on A/B/C and submit immediately, remove the normal submit button and just give A/B/C type=submit.
So far what I understand form your question is that you want to POST the value of the button that is clicked. In this case you do not need a submit button. You can do it when a button is clicked. You can do it in following way:
$(".btn_quick_select").click(function(){
var btnValue = $(this).val();
//code to POST btnValue goes here...
});
Otherwise, if you want to submit then you can't do it using button. Use checkbox or radio instead. Then your markup will be look like this:
Let me konw if it is helpful for you.
<form action="thecontroller/post" method="post" id="buttons">
<div class="select_direct">
<input type="checkbox" name="xyz" value="value1">
<input type="checkbox" name="xyz" value="value2">
<input type="checkbox" name="xyz" value="value3">
</div>
<button type="submit" name="add">
</form>
And JavaScript:
$("#buttons").submit(function(e){
e.preventDefault();
var btnValue = $(this).serialize();
//code to POST btnValue goes here...
});
Hope it will be helpful. Let me know about it.

each function jquery don't work

hi I've this html code
<html>
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/sunny/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<link href="stile.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css">
</head>
<body>
<form action="">
<div>
<div style="float:left; margin-right:3%">XXX</div>
<div>
<input type="text" name="price" id="price" value="2">
</div>
<div style="float:left; margin-right:3%">
<input type="button" name="button" id="button" value="button">
</div>
</div>
<div>
<div style="float:left; margin-right:3%">YYY</div>
<div>
<input type="text" name="price" id="price" value="3">
</div>
<div style="float:left; margin-right:3%">
<input type="button" name="button" id="button" value="button">
</div>
</div>
<div id="total"></div>
<script src="js/mine.js"></script>
</form>
</body>
</html>
and the follow js code in the file mine.js
$("#button").each(function() {
var sum = 0;
$('#price').each(function() {
sum += Number($(this).val());
});
$('#total').text(sum);
});
I'd like that when I click on button in the div id total it gives me the value of the field price.
So if I click on the first submit button it gives me the value 2 but if after I click on the second button it doesnt do the sum (2+3=5)
You should use class instead of id as jquery id selector (#) only returns one element
https://api.jquery.com/id-selector/
For id selectors, jQuery uses the JavaScript function
document.getElementById(), which is extremely efficient. When another
selector is attached to the id selector, such as h2#pageTitle, jQuery
performs an additional check before identifying the element as a
match.
Calling jQuery() (or $()) with an id selector as its argument will
return a jQuery object containing a collection of either zero or one
DOM element.
Inputs would be
<input type="text" name="price" class="price" value="2">
<input type="button" name="button" class="button" value="button">
In the case of total you can leave the id as you would have one final total
So your code would be something like this
$(".button").each(function() {
var sum = 0;
$('.price').each(function() {
sum += Number($(this).val());
});
$('#total').text(sum);
});
UPDATE :
If you use this code and click first button it would give 2 and then the other one it would give 5. You can try disabling click handler in order to prevent from adding a second time.
$(document).on("click", ".button", function()
{
var sum = Number($('#total').text());
sum += Number($(this).closest("div").parent().find('.price').val());
$('#total').text(sum);
});
Addenda : Quantity input that increases each time button is pressed
<div>
<input type="text" name="quantity" class="quantity" value="0">
<input type="button" class="add-quantity">
</div>
$(document).on("click", ".add-quantity", function()
{
var input = $(this).closest("div").find(".quantity");
var currentVal = parseInt(input.val());
$(input).val(currentVal+1);
});
So looking at your code, you've got the following:
<input type="button" name="button" id="button" value="button"></div>
<div><input type="text" name="price" id="price" value="2"></div>
<input type="button" name="button" id="button" value="button"></div>
<div><input type="text" name="price" id="price" value="3"></div>
You've got button and id set twice as id's and you should have unique id's, so when you're check for each element use class= instead of id=.
So if you was to make that change, they would look like the following:
<input type="button" name="button" class="button" value="button"></div>
<div><input type="text" name="price" class="price" value="2"></div>
<input type="button" name="button" class="button" value="button"></div>
<div><input type="text" name="price" class="price" value="3"></div>
Then you would use $('.button') and $('.price') instead of $('#button') and $('#price') for the selectors in JQuery.
I've taken your fiddle and updated it.
Check the following:
JSFIDDLE
UPDATE
After reading your comment, i've updated my jsfiddle and you can now click the two buttons and then have the answer add up to (5)
The reason it was adding up to (5) straight away without you clicking the buttons was because it was doing the .each instead of you having to click the buttons yourself.
So to do this i've used two different classes for the buttons and inputs so they would like the following:
<input type="button" name="button" class="button" value="button"></div>
<div><input type="text" name="price" class="price" value="2"></div>
<input type="button" name="button" class="button1" value="button"></div>
<div><input type="text" name="price" class="price1" value="3"></div>
UPDATED JSFIDDLE
Every click will keep adding the value on to the total number because there no validation to tell the click to stop once it's added up to (5)
UPDATE USING ONE BUTTON
You could even do this, instead of having two buttons, you could just have one button which goes through each of the inputs and adds up the total.
for example:
JSFIDDLE EXAMPLE WITH ONE BUTTON
UPDATE USING TWO BUTTON (Same class names and Validation for 5)
So in the following update (example) it will show you how to get both values using the same class names for both buttons and inputs. It will also show you how to add little validation to stop the adding up once you have 5. So you can't go over 5 (Change it how you like).
JSFIDDLE WITH TWO BUTTONS AND LITTLE VALIDATION

How do I write JavaScript that validates input across multiple forms?

I am attempting to write JavaScript that traverses multiple HTML forms, checks an input for a given value on edit, then enables/disables the submit button for that form based on the input value.
I have a very simple example script, which overrides the onclick function of checkboxes, to test the flow of my code.
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<script type="text/javascript">
forms = document.getElementsByTagName("form");
for(i=0; i<forms.length; i++)
{
inputs = forms.item(i).getElementsByTagName("input");
inputs.item(0).onclick = function()
{
if(this.checked)
inputs.item(1).removeAttribute("disabled");
else
inputs.item(1).setAttribute("disabled","disabled");
}
}
</script>
What I expect to happen: the checkboxes change the value of the submit button in the same form.
What actually happens: all the checkboxes change the value of the submit button in the last form.
The actual code will be somewhat smarter, but I want to understand the flow of JavaScript code before progressing onto something more complex.
Thanks in advance!
Try something like this:
document.body.onchange = function(e) {
// this delegates all the way to the body - if you have a more specific
// container, prefer using that instead.
e = e || window.event;
var t = e.srcElement || e.target;
if( t.nodeName == "INPUT" && t.type == "checkbox") {
// may want to add a className to the checkboxes for more specificity
t.parentNode.getElementsByTagName('input')[1].disabled = !t.checked;
}
};
The reason you are seeing the behaviour you're getting is because inputs' value is not fixed, you are repeatedly re-assigning it to the next form's elements, ultimately resulting in the last one.

How to manually check a YUI radio "button"

<script type="text/javascript">
(function () {
var ButtonGroup = YAHOO.widget.ButtonGroup;
var onCheckedButtonChange = function (p_oEvent) {
};
YAHOO.util.Event.onContentReady("mediaFilterButtonsFieldset", function () {
var oButtonGroup = new ButtonGroup("mediaFilterButtons");
oButtonGroup.on("checkedButtonChange", onCheckedButtonChange);
});
}());
</script>
<div id="resultInfo">
<form id="button-example-form" name="button-example-form" method="post">
<fieldset id="mediaFilterButtonsFieldset">
<div id="mediaFilterButtons" class="yui-buttongroup ie7filter" style="z-index:11;">
<div id="mediaFilterLabel">Go to</div>
<input id="radio1" class="filter_but" type="radio" name="0" value="First" checked rel="0" >
<input id="radio2" class="filter_but" type="radio" name="2" value="Second" rel="2">
<input id="radio3" class="filter_but" type="radio" name="1" value="Third" rel="1">
</div>
</fieldset>
</form>
</div>
These are my YUI buttons. They're just 3 radio buttons turned into "buttons"--literally. My question is this:
After people click the third button, I cannot manually check the first button anymore. How can I manually check "radio1"?
Edit:
According to the official YUI website, there is a method called "set". But I don't know how to use that in this buttonGroup.
The radio buttons must all have the same name attribute in order for them to be grouped together.
Answering your question with the set method. Perhaps this does the trick:
YAHOO.one("#radio1").set("checked",true);
To manually check the radio buttons, it's necessary to have the same name of radio button. Put the same name of radio button and get your result.

Categories

Resources