How to have multiple radio buttons with different functionality? - javascript

I am working on a project in which I need to make an HTML page with couple of radio buttons.
First radio button is, INSERT. As soon as I click INSERT radio button, I would like to show three text box just below the INSERT radio button. First textbox is datacenter, second textbox is node and third textbox is data.
Second radio button is, UPDATE. As soon as I click UPDATE radio button, I would like to show same above three text box just below the UPDATE radio button.
Third radio button is, DELETE. As soon as I click DELETE radio button, I would like to show only one text box just below the DELETE radio button. In this one text box will be node.
Fourth radio button is, PROCESS. As soon as I click PROCESS radio button, I would like to show four text box just below the PROCESS radio button. In this first textbox will be datacenter, second textbox will be node, third textbox will be conf and fourth textbox will be data.
I am able to make first two radio button work (insert and update) but somehow I am not able to understand how do I make last two radio button work.
Below is my HTML
<form method="post" action="testOperation">
<input type="hidden" name="name" id="dynamicName">
<input class="changeAction" type="radio" name="tt" value="Insert" div-id="insert"/> Insert
<div id="insert" class="changeable"></div>
<br/> <input class="changeAction" type="radio" name="tt" value="Update" div-id="update"/> Update
<div id="update" class="changeable"></div>
<br/>
<input type="submit">
</form>
Below is my jquery -
$(document).ready(function(){
$(".changeAction").on("click", function(){
$('.changeable').html('')
var divId = $(this).attr("div-id");
$("#dynamicName").val(divId);
divId = "#"+divId;
var myInput = '<label for="Datacenter"> Datacenter </label> <input type="text" name="datacenter" size="20" /> <label for="Node"> Node </label> <input type="text" name="node" size="20" /> <label for="Data"> Data </label> <input type="text" name="data" size="100"/>'
$(divId).html(myInput);
})
})
And here is my jsfiddle. It will be of great help if anyone can provide any jsfiddle example?

try this code in javascript part,
var datacenter = '<label for="Datacenter"> Datacenter </label> <input type="text" name="datacenter" size="20" />';
var node = '<label for="Node"> Node </label> <input type="text" name="node" size="20" />';
var data = '<label for="Data"> Data </label> <input type="text" name="data" size="100"/>';
var config = '<label for="Config"> Config </label> <input type="text" name="config" size="100"/>';
$(".changeAction").on("click", function () {
var divId = $(this).attr("div-id");
$('.changeable').html('');
$("#dynamicName").val(divId);
switch (divId) {
case 'insert':
//insert stuff goes here!!
divId = "#" + divId;
var myInput = datacenter + node + data;
$(divId).html(myInput);
break;
case 'update':
//update stuff goes here!!
divId = "#" + divId;
var myInput = datacenter + node + data;
$(divId).html(myInput);
break;
case 'Delete':
//Delete stuff goes here!!
divId = "#" + divId;
var myInput = node;
$(divId).html(myInput);
break;
case 'process':
//process stuff goes here!!
divId = "#" + divId;
var myInput = datacenter + node + config + data;
$(divId).html(myInput);
break;
}
});
SEE FIDDLE DEMO

Change your html code to this
<input class="changeAction" type="radio" name="tt" value="Insert" div-id="insert"/> Insert
<div id="insert" class="changeable"></div>
<br/> <input class="changeAction" type="radio" name="tt" value="Update" div-id="update"/> Update
<div id="update" class="changeable"></div><br/>
<input class="changeAction" type="radio" name="tt" value="Delete" div-id="delete"/> Delete
<div id="delete" class="changeable"></div>
<br/> <input class="changeAction" type="radio" name="tt" value="Process" div-id="process"/> Process
<div id="process" class="changeable"></div>
<br/>
<input type="submit">
</form>

Related

Creating multiple elements (input) on button press, within a loop

My goal with this is to have forms that contain a beginning input, and if the '+' button next to it is pressed, it will create another input below it. All of these inputs will eventually be inserted in AJAX.
Right now my form is inside a PHP foreach loop, so I have multiple forms, each with their own set of inputs and buttons.
If I click the '+' button in each form, it will create a new input below, but the way I'm trying to limit each form to 10 inputs, it's going across all forms like this:
So in that image, I clicked the '+' button of the first form 3 times (up to item 4) and then I pressed it in the next form which gave Item 5.
The functionality is basically working here, but I need each form to have it's own inputs, limited to 10. This way if they save items on any form, I can pass only those inputs to AJAX.
<form id="Items" method="post">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]"><br/>
<button type="button" class="moreItems_add" onclick="moreItems(this);">+</button>
<input type="hidden" name="tickerID" id="tickerID" value="xyz">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
<!-- ticker modal JS -->
<script type="text/javascript">
var maxItems = 1;
function moreItems(button) {
if (maxItems < 10) {
var label = document.createElement("label");
label.id="ItemLabel"+maxItems;
label.innerHTML = "Item "+(maxItems+1)+": ";
var input = document.createElement("input");
input.type='text';
input.name = 'item'+maxItems;
$($(label)).insertBefore($(button));
$($(input)).insertBefore($(button));
//Insert a line break so that the next label and input are on new line
$('<br/>').insertBefore($(button));
maxItems++;
}
}
</script>
You're using a global variable as your counter so it will increment with every use for every form. Why not have the button check what's in the form and do the counting itself? And while you're at it, may as well go full jQuery.
$("button.moreItems_add").on("click", function(e) {
var numItems = $("input[type='text']", $(this).closest("form")).length;
if (numItems < 10) {
var html = '<label class="ItemLabel">Item ' + (numItems + 1) + ': </label>';
html += '<input type="text" name="Items[]"/><br/>';
$(this).before(html);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="Items" method="post">
<label class="ItemLabel">Item 1:</label>
<input type="text" name="Items[]"><br/>
<button type="button" class="moreItems_add">+</button>
<input type="hidden" name="tickerID" id="tickerID" value="xyz">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
Also you were naming your text inputs sequentially, which I assume was a mistake?
Here's a solution after a couple modifications to your code.
function moreItems(button) {
var maxItems = Number(button.attributes.cnt.value);
maxItems += 1;
button.setAttribute("cnt", maxItems);
if (maxItems < 10) {
var label = document.createElement("label");
label.id = "ItemLabel" + maxItems;
label.innerHTML = "Item " + (maxItems + 1) + ": ";
var input = document.createElement("input");
input.type = 'text';
input.name = 'item' + maxItems;
$($(label)).insertBefore($(button));
$($(input)).insertBefore($(button));
$('<br/>').insertBefore($(button));
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="Items" method="post">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]"><br/>
<button type="button" cnt="0" class="moreItems_add" onclick="moreItems(this);">+</button>
<input type="hidden" name="tickerID" id="tickerID">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
<br><br>
<form id="Items" method="post">
<label id="ItemLabel2">Item 1:</label>
<input type="text" name="Items[]"><br/>
<button type="button" cnt="0" class="moreItems_add" onclick="moreItems(this);">+</button>
<input type="hidden" name="tickerID" id="tickerID2">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
Changes made:
add a custom attribute to each + button, in here cnt="0".
in moreItems() function, increment value of cnt of respective form's + button.

How to access a different page when a user has selected a checkbox and click a button?

I have three checkbox for the users to select from. The third checkbox when it is selected display a form which allows the users to fill in a form and submit it as an email which is working. However what I wanted to do for the other two is to allow the users select any checkbox and then click on button which will take to their appropriate web pages. For example if a user select the checkbox to upload a file and then click a button "next" it will then then take them to the upload file web page.
I am still learning jquery so i would like a bit of help with the jquery/javascript code if it is possible. I have made attempt on the jquery code however i know im doing it right.
<form action="">
<input type="checkbox" name="radio-1" id="radio-1" onchange = "changeRadio()">
<label for="radio-1">I Want to Upload my own artwork</label>
</br>
<input type="checkbox" name="radio-1" id="radio-1" onclick =>
<label for="radio-1">I want to use a pre made template</label>
</br>
<input type="checkbox" name="createartwork" id="createartwork">
<label class="label-for-check" for="createartwork">I want you to create my artwork</label>
</form>
<div id="next-container">
<button class="card__btn btn" id="nxtBtn" type="button" >Next</button>
</div>
$(function() {
$('#radio-1').click(function() {
$('#nxtBtn').prop(
'disabled',
(!$(this).prop('checked'))
);
});
});
My suggestion here would be to change checkbox to radio-group with same name, and add a click event to #nextBtn button and get the selected value from radio group and based on the value, perform necessary action. To navigate to different page just use location.href="your url";. Below is the sample demo snippet for you.
$("#nxtBtn").on('click', function() {
var selected = $('input[name=radio-1]:checked', '#frmOptions').val()
switch (selected) {
case "1":
alert("Redirect with location.href='www.someurl.com/newpage';");
//replace alert with location.href="your url";
break;
case "2":
alert("Redirect with location.href='www.someurl.com/newpage2';");
//replace alert with location.href="your url";
break;
case "3":
alert("Display Your form");
break;
default:
break;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="frmOptions" action="">
<input type="radio" value="1" checked name="radio-1" id="radio-1" />
<label for="radio-1">I Want to Upload my own artwork</label>
<br/>
<input type="radio" value="2" name="radio-1" id="radio-2" />
<label for="radio-2">I want to use a pre made template</label>
<br/>
<input type="radio" value="3" name="radio-1" id="createartwork">
<label class="label-for-check" for="createartwork">I want you to create my artwork</label>
<br/>
<div id="next-container">
<button class="card__btn btn" id="nxtBtn" type="button">Next</button>
</div>
</form>
You could hide the Next button until an option is selected, this will force the user to make a selection before proceeding. The following solution will set the form action based upon the radio button selection.
<style>
.hidden {
visibility: hidden;
}
</style>
<script>
$().ready(function() {
$("input[name=artwork]:radio").click(function() {
var url = "http://url.com/default";
// get the value from the input field
switch(this.value) {
case "create" :
url = "http://url.com/create";
break;
case "premade" :
url = "http://url.com/premade";
break;
case "upload" :
url = "http://url.com/upload";
break;
});
// set the form target
$("#artwork_form").attr("target", url);
// display the button container
$("#next-container").removeClass("hidden");
}
});
</script>
<form name="artwork_form" id="artwork_form" action="">
<input type="radio" name="artwork" value="upload">
<label>I Want to Upload my own artwork</label>
<br/>
<input type="radio" name="artwork" value="premade">
<label>I want to use a pre made template</label>
<br/>
<input type="radio" name="artwork" value="create">
<label>I want you to create my artwork</label>
<br/>
<br/>
<div id="next-container" class="hidden">
<input type="submit" id="nxtBtn" value="Next">
</div>
</form>

Type on textfield when it has focus using button Javascript

I have one button that displays number "1" when clicked and three text boxes. I want when the button is clicked the number is displayed on the text box that has focus. Can someone help me please.
function run(){
document.calc.txt1.value += "1";
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1">
<input type="text" id="txt2" name="txt2">
<input type="text" id="txt3" name="txt3">
</form>
t3">
When you click a button, the previous input looses focus. You could try to store the last focused input element before the click:
(this needs some more work)
var lastFocus = null;
document.addEventListener("blur", function(event) {
// Here, you'll need to find out if the blurred element
// was one of your valid inputs. It's probably best to
// identify them by a class name
if (event.target.type === "text") {
lastFocus = event.target;
}
}, true);
function run() {
// When the user hasn't yet focused on a text input,
// the first one is used by default
(lastFocus || document.calc.txt1).value += "1";
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1">
<input type="text" id="txt2" name="txt2">
<input type="text" id="txt3" name="txt3">
</form>
var currId;
function setId(curr){
currId=curr.id;
}
function run(){
if(currId)
{
document.getElementById(currId).value +='1';
}
//document.calc.txt1.value += "1";
//document.activeElement.value += "1";
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1" onblur="setId(this)">
<input type="text" id="txt2" name="txt2" onblur="setId(this)">
<input type="text" id="txt3" name="txt3" onblur="setId(this)">
</form>
Ok, so this code snippet should do what you want. The main thing to note though is that whenever you click the button, the input box becomes blurred that you had selected.
Essentially what this code does here is set the onfocus attribute to allow you to figure out which input box was last focused, rather than which input box IS focused, because none are. Also, I'd recommend changing the button to a 'button' tag because it separates it in terms of tag name from the other input boxes.
Hope this helped, and let me know if you have any questions.
var inputs = document.getElementsByTagName('input');
for(var i = 1 ; i < inputs.length; i ++){
inputs[i].onfocus = function(){
this.setAttribute('class','focused');
}
}
function run(){
var inputBox = document.getElementsByClassName('focused')[0];
if(inputBox){
inputBox.value += "1";
inputBox.setAttribute('class','blurred');
}
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1">
<input type="text" id="txt2" name="txt2">
<input type="text" id="txt3" name="txt3">
</form>

Store input radio selections when submit is clicked

I need to store in my js file which radio option for each radio name was selected as well as store the Username that was entered. Here is my form
<form id="newPlayer">
Username:<br>
<input type="text" name="user"/><br>
Please Choose a Class: <br>
<input type="radio" name="class"/>Archer
<input type="radio" name="class"/>Mage
<input type="radio" name="class"/>Warrior
<br>
Please Choose a Race: <br>
<input type="radio" name="race"/>Orc
<input type="radio" name="race"/>Elf
<input type="radio" name="race"/>Human
<input type="radio" name="race"/>Worg
<br>
<input type="submit" value="Submit">
</form>
EDIT:
When I try to target the submit button for a click function it causes my page to reload instead of making the form fadeOut
var userInput;
var classInput;
var raceInput;
$('input[type=submit]').click(function(){
$('#newPlayer').fadeOut(500);
userInput = $('input[name="user"]').val();
classInput = $('input[name="class"]:checked').val();
raceInput = $('input[name="race"]:checked').val();
});
Maybe this helps. First, you will have to put values on those inputs
<form id="newPlayer">
Username:<br>
<input type="text" name="user"/><br>
Please Choose a Class: <br>
<input value="archer" type="radio" name="class"/>Archer
<input value="mage" type="radio" name="class"/>Mage
<input value="warrior" type="radio" name="class"/>Warrior
<br>
Please Choose a Race: <br>
<input value="orc" type="radio" name="race"/>Orc
<input value="elf" type="radio" name="race"/>Elf
<input value="human" type="radio" name="race"/>Human
<input value="worg" type="radio" name="race"/>Worg
<br>
<input type="submit" value="Submit">
</form>
Then, using jQuery, a simple .val() will do the job:
var class_val = $('input[name="class"]:checked').val();
var race = $('input[name="race"]:checked').val();
var user = $('input[name="user"]').val();
After that, you just need to put in localStorage
localStorage.setItem('class', class_val);
localStorage.setItem('race', race);
localStorage.setItem('user', user);
To access those values in the future, you do that
var stored_class = localStorage.getItem('class');
var stored_race = localStorage.getItem('race');
var stored_user = localStorage.getItem('user');
To make things happens on submit, you add an submit event to the form, like that:
$('form').on('submit', function() {
// Get values
var class_val = $('input[name="class"]:checked').val();
...
// Store values
localStorage.setItem('class', class_val);
...
// Avoid form submit
return false;
});
Hope it helps :)
I think I would use localStorage.
For example:
//Make sure to set the selection variable to a object that contains the selections made by the user.
function save() {
//This will save the current settings as an object to the localStorage.
localStorage.selections = JSON.stringify(selections) ;
}
function load() {
if (!localStorage.selections) {
alart("No saves found.") ;
return false ;
}
selections = JSON.parse(localStorage.selections) ;
}
Read more about localStorage here.

Javascript adding values to radio buttons to input price

Im trying to create a javascript block inside of a webpage im working on. I havent done javascript since highschool and it doesnt seem to want to come back to me :(
In this block of code i want to have 4 sets of radio buttons, each time a selection is picked,
a price will be inputed to a variable for each radio group. i.e
var firstPrice = $25
var secondPrice = $56
var thirdPrice = $80
var fourthPrice = $90
then after each radio group has one selection there will be a function attached to the submit button that adds up each price to display the final amount inside of a hidden field
var totalPrice = (firstPrice + secondPrice + thirdPrice + fourthPrice)
My question is, how do i attach a number value to a radio button within a group, same name but id is different in each group. Then do i just create a function that adds all the price groups up and then set the submit button to onClick = totalPrice();
Here is an example of one set of radio buttons:
<label>
<input type="radio" name="model" value="radio" id="item_0" />
item 1</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_1" />
item2</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_2" />
item3</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_3" />
Item4</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_4" />
item5</label>
</form>
then my script looks something like:
function finalPrice90{
var selectionFirst = document.modelGroup.value;
var selectionSecond = document.secondGroup.value;
var selectionThird = document.thirdGroup.value;
var selectionFourth = document.fourthGroup.Value;
var totalPrice = (selectionFirst + selectionSecond + selectionThird + selectionFourth);
}
Try this fiddle
http://jsfiddle.net/tariqulazam/ZLQXB/
Set the value attribute of your radio inputs to the price each radio button should represent.
When it's time to calculate, simply loop through each group and get the value attribute if the checked radio.
Because the value attribute is a string representation of a number, you'll want to convert it back to a number before doing any math (but that's a simple parseInt or parseFloat).
Here's a working fiddle using pure JavaScript: http://jsfiddle.net/XxZwm/
A library like jQuery or Prototype (or MooTools, script.aculo.us, etc) may make this easier in the long run, depending on how much DOM manipulation code you don't want to re-invent a wheel for.
Your requirements seem pretty simple, here's an example that should answer most questions. There is a single click listener on the form so whenever there is a click on a form control, the price will be updated.
<script type="text/javascript">
//function updatePrice(el) {
function updatePrice(event) {
var el = event.target || event.srcElement;
var form = el.form;
if (!form) return;
var control, controls = form.elements;
var totalPrice = 0;
var radios;
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
if ((control.type == 'radio' || control.type == 'checkbox') && control.checked) {
totalPrice += Number(control.value);
}
// Deal with other types of controls if necessary
}
form.totalPrice.value = '$' + totalPrice;
}
</script>
<form>
<fieldset><legend>Model 1</legend>
<input type="radio" name="model1" value="25">$25<br>
<input type="radio" name="model1" value="35">$35<br>
<input type="radio" name="model1" value="45">$45<br>
<input type="radio" name="model1" value="55">$55<br>
</fieldset>
<fieldset><legend>Model 2</legend>
<input type="radio" name="model2" value="1">$1<br>
<input type="radio" name="model2" value="2">$2<br>
<input type="radio" name="model2" value="3">$3<br>
<input type="radio" name="model2" value="4">$4<br>
<fieldset><legend>Include shipping?</legend>
<span>$5</span><input type="checkbox" value="5" name="shipping"><br>
</fieldset>
<input name="totalPrice" readonly><br>
<input type="reset" value="Clear form">
</form>
You could put a single listener on the form for click events and update the price automatically, in that case you can get rid of the update button.

Categories

Resources