Javascript DIV not updating on change - javascript

I am attempting to make a page where the usere can chose between two products and enter some text in two fields which will append on the end of a link. My page works If I enter the text first and then chose the option however if I select the product option first the text doesn't append and if I try to update the text in the fields once the link is shown, it remains the same. I'm a bit of a beginner to JavaScript so any suggestions as to where I am going wrong would be greatly appreciated?
<html>
<head>
<script type="text/javascript">
function productChange(product) {
var val = product.value
var idTag = document.getElementById("idTag");
var trackingTag = document.getElementById("trackingTag");
if (val == 'Movies') {
document.getElementById('divProductChangeLinkTitle').innerHTML = '<span style="color: #680091;">Your movies link is:</span>';
document.getElementById('divProductChangeFinalMovLink').innerHTML = 'https://www.link/MOVIES?cid=' + idTag.value + '&omniture=' + trackingTag.value;
} else {
document.getElementById('divProductChangeLinkTitle').innerHTML = '<span style="color: #FF7000;">Your ents link is:</span>';
document.getElementById('divProductChangeFinalMovLink').innerHTML = 'https://www.link/ENTS?cid=' + idTag.value + '&omniture=' + trackingTag.value;
}
}
</script>
</head>
<body>
Movies: <input name="ProductRadio" type="radio" value="Movies" onclick='productChange(this)' id="MoviesRadio" /><br>
Ents: <input name="ProductRadio" type="radio" value="Entertainment" onclick='productChange(this)' id="EntsRadio" />
<br><br>
ID: <input type="text" id="idTag" onchange="productChange()"><br>
Tracking: <input type="text" id="trackingTag" onchange="productChange()">
<br><br>
<div align="center" id="divProductChangeLinkTitle"></div>
<br><br>
<div id="divProductChangeFinalMovLink" style="color: #000000;"></div>
</body>
</html>

In your method, when onChange event occurs for input text, then val is undefined, because you are not passing anything, so in productChange() method, you can get radio button values directly, I have made some changes in your code, please check fiddle -
HTML -
Movies: <input name="ProductRadio" type="radio" value="Movies" onclick='productChange()' id="MoviesRadio" /><br>
Ents: <input name="ProductRadio" type="radio" value="Entertainment" onclick='productChange()' id="EntsRadio" />
<br><br>
ID: <input type="text" id="idTag" onchange="productChange()"><br>
Tracking: <input type="text" id="trackingTag" onchange="productChange()">
<br><br>
<div align="center" id="divProductChangeLinkTitle"></div>
<br><br>
<div id="divProductChangeFinalMovLink" style="color: #000000;"></div>
Javascript -
function productChange() {
var val = document.querySelector('input[type="radio"][name="ProductRadio"]:checked').value;
var idTag = document.getElementById("idTag").value;
var trackingTag = document.getElementById("trackingTag").value;
if (val == 'Movies' && idTag && trackingTag) {
document.getElementById('divProductChangeLinkTitle').innerHTML = '<span style="color: #680091;">Your movies link is:</span>';
document.getElementById('divProductChangeFinalMovLink').innerHTML = 'https://www.link/MOVIES?cid=' + idTag + '&omniture=' + trackingTag;
} else if(val=='Entertainment' && idTag && trackingTag){
document.getElementById('divProductChangeLinkTitle').innerHTML = '<span style="color: #FF7000;">Your ents link is:</span>';
document.getElementById('divProductChangeFinalMovLink').innerHTML = 'https://www.link/ENTS?cid=' + idTag + '&omniture=' + trackingTag;
}
}
Now, if radio button is selected and both inputs have some value then only link will be shown

Hey the above code is working , but you to also set one condition to check atleast one radio button then fill the input values else on direct filling those input text fields it is giving error.
So one radio button needs to be checked.

<html>
<head>
<script type="text/javascript">
function productChange(product) {
var val = document.querySelector('input[type="radio"][name="ProductRadio"]:checked').value;
var idTag = document.getElementById("idTag");
var trackingTag = document.getElementById("trackingTag");
if (val == 'Movies') {
document.getElementById('divProductChangeLinkTitle').innerHTML = '<span style="color: #680091;">Your movies link is:</span>';
document.getElementById('divProductChangeFinalMovLink').innerHTML = 'https://www.link/MOVIES?cid=' + idTag.value + '&omniture=' + trackingTag.value;
} else {
document.getElementById('divProductChangeLinkTitle').innerHTML = '<span style="color: #FF7000;">Your ents link is:</span>';
document.getElementById('divProductChangeFinalMovLink').innerHTML = 'https://www.link/ENTS?cid=' + idTag.value + '&omniture=' + trackingTag.value;
}
}
</script>
</head>
<body>
Movies: <input name="ProductRadio" type="radio" value="Movies" onclick='productChange(this)' id="MoviesRadio" /><br>
Ents: <input name="ProductRadio" type="radio" value="Entertainment" onclick='productChange(this)' id="EntsRadio" />
<br><br>
ID: <input type="text" id="idTag" onchange="productChange()"><br>
Tracking: <input type="text" id="trackingTag" onchange="productChange()">
<br><br>
<div align="center" id="divProductChangeLinkTitle"></div>
<br><br>
<div id="divProductChangeFinalMovLink" style="color: #000000;"></div>
</body>
</html>
You need to pass value while calling productChange function.

Related

Using JavaScript to store user input from a form into an array of records

This is a problem for school. I need to make an array of records to store user input that loops the number of times the user specifies.
1 - The user will enter the number of volunteers (between 5-10). I have that part working.
2 - The input form is suppose to display the number of times as the number of volunteers. I'm not sure how to do that.
3 - The user's input is to be stored in an array of records.
4 - A message is to be displayed at the bottom with each volunteer's inputted information.
I'm stuck on number 2 and I'm positive I'll need help with 3 & 4 too.
Any assistance would be greatly appreciated.
You can see the code I've written below and I've included the JS code for both functions that I have working (validateForm() & getNumberOfVolunteers())
function getNumberOfVolunteers() {
var y = document.forms["numberOfVolunteersForm"]["numberOfVolunteers"].value;
if (y == "") {
alert("Number of volunteers must be filled out.");
return false;
}
document.getElementById("numberOfVolunteers1").innerHTML = y;
return false;
}
function validateForm() {
var a = document.forms["inviteForm"]["recipientName"].value;
if (a == "") {
alert("Name must be filled out.");
return false;
}
var b = document.forms["inviteForm"]["organizationName"].value;
if (b == "") {
alert("Organization name must be filled out.");
return false;
}
document.getElementById("recipientName1").textContent = a;
document.getElementById("organizationName1").textContent = b;
return false;
}
<!DOCTYPE html>
<html lang="en-US">
<!--
<head>
<script src="js/getNumberOfVolunteers.js"></script>
</head>
-->
<body>
<header>
</header>
<section id="numOfVolunteers">
<form name="numberOfVolunteersForm" onsubmit="return getNumberOfVolunteers()">
<label for="numberOfVolunteers">Number of volunteers:
</label>
<input type="number" min="5" max="10" value="5" name="numberOfVolunteers" id="numberOfVolunteers" placeholder="Enter the number of volunteers" />
<input type="submit" value="submit" id="submit1" />
</form>
</section>
<section id="pageForm">
<form action="#" name=inviteForm onsubmit="return getVolunteerInfoIntoArray()">
Number of Volunteers Entered: <strong><span id="numberOfVolunteers1"> </span></strong> <br/> <br/>
<label for="recipientName">Recipient name:
</label>
<input type="text" name="recipientName" id="recipientName" placeholder="Enter your Recipient Name" />
<label for="organizationName">Organization name:
</label>
<input type="text" name="organizationName" id="organizationName" placeholder="Enter your Organization Name" />
<input type="submit" value="submit" id="submit2" onclick="validateForm" />
</form>
</section>
<article id="placeholderContent">
Hello <span id="recipientName1"></span>!
<br/>
<br/> You have been invited to volunteer for an event held by <span id="organizationName1"></span>
</article>
<script>
var volunteerArray = [];
function getVolunteerInfoIntoArray() {
var volCount;
for (volCount = 5; volCount < getNumberOfVolunteers1.length; volCount++);
document.getElementById('recipientName');
document.getElementById('organizationName');
volunteerArray.push([recipientName.value, organizationName.value]);
}
</script>
</body>
</html>
I need to display the input form and the article multiple times. And store all the input in an array.
Is this what you're trying to do? Hope this helps even it's not exactly what you want hahahah
<!DOCTYPE html>
<html lang="en-US">
<head>
<style>
.numberofvolunteers,
.all-volunteers{
padding:10px;
}
input,button{
margin:3px;
}
span{
font-size:12px;
padding:10px 10px;
}
</style>
</head>
<body>
<div class="numberofvolunteers">
<input type="number" id="volunteers" placeholder="Enter No. of volunteers"><button onclick="createVolunteerForm()">Submit</button>
</div>
<div id="all-volunteers">
</div>
<span id="array"></span>
<script>
var volunteerArray = [];
function createVolunteerForm(){
volunteerArray = [];
var numberofvolunteers = document.getElementById("volunteers").value;
var content = "";
if(parseInt(numberofvolunteers) < 5 || parseInt(numberofvolunteers) > 10){
alert("No. of volunteer should be 5 to 10");
}
else{
for(var i = 0; i < parseInt(numberofvolunteers); i++){
content += createForm(i);
}
}
document.getElementById("all-volunteers").innerHTML = content;
}
function createForm(index){
var content = ' <div id="volunteer-div-'+index+'">'+
'<div id="volunteer-form-'+index+'">'+
'<input type="text" id=recipient-'+index+' placeholder="Enter recipient name">'+
'<input type="text" id=organization-'+index+' placeholder="Enter organization name">'+
'<button id="submit-'+index+'" onclick="displayMessage('+index+');addToArray('+index+');">submit</button>'+
'</div>'+
'<span id="message-'+index+'"></span>'+
'</div>';
return content;
}
function displayMessage(index){
var message = "Hello " + document.getElementById("recipient-"+index).value + " your organization is " + document.getElementById("organization-"+index).value;
document.getElementById("message-" + index).innerHTML = message;
}
function addToArray(index){
volunteerArray.push({recipient : document.getElementById("recipient-"+index).value , organization : document.getElementById("organization-"+index).value});
document.getElementById("array").innerHTML = JSON.stringify(volunteerArray);
}
</script>
</body>
</html>

How to set paragraph to textbox text

Let us say I have an HTML form, with two textboxes, I want to add the two numbers in the two textboxes and display the result in a paragraph. How can I do that?
Change paragraph according to textbox is what I can't find!
Very simple:
document.getElementById('sum').onsubmit = add;
function add(e) {
e.preventDefault();
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
var result = 'Result: ' + String(parseInt(num1) + parseInt(num2));
var p = document.getElementById('result');
p.innerHTML = result;
}
<form id="sum">
<label for="num1">First number:</label>
<br />
<input type="text" id="num1" />
<br />
<label for="num1">Second number:</label>
<br />
<input type="text" id="num2" />
<br />
<input type="submit" value="Add" />
</form>
<p id="result">Result:</p>
In the html we have a form with 3 inputs, 2 are type text and one is type submit. and also a paragraph.
In the javascript we assign to the form's onsumbit event the function add(), in the function we prevent the default so the form wont refresh the page, then we get the 2 values that were inputed, create a string that would contain the sum of those values and set the paragraph's innerHTML to it.
Create a calculator function and then you can fire it on keyup or you can assign it to a button if you'd like.
function calcTotal(){
var inputs = document.getElementsByTagName('input'),
result = 0;
for(var i=0;i<inputs.length;i++){
if(parseInt(inputs[i].value))
result += parseInt(inputs[i].value);
}
document.getElementById('total').innerHTML = 'Total: ' + result;
}
<form>
<input onkeyup="calcTotal()" type="text" />
<input onkeyup="calcTotal()" type="text" />
</form>
<p id="total"></p>
follow bellow JS code:
<html>
<head>
<title>Sum Two Number</title>
<script language="javascript">
function addNumbers()
{
var val1 = parseInt(document.getElementById("value1").value);
var val2 = parseInt(document.getElementById("value2").value);
if(val1 !== "" && val2 !== "") {
var result = val1 + val2;
document.getElementById('result').innerHTML = result;
}
}
</script>
</head>
<body>
value1 = <input type="text" id="value1" name="value1" value="0" onkeyup="javascript:addNumbers()"/>
value2 = <input type="text" id="value2" name="value2" value="0" onkeyup="javascript:addNumbers()"/>
<p>Answer = <span id="result"></span></p>
</body>
</html>
In this example, you have a form with 2 input. When you press on a button, the value of those 2 input is added inside a paragraph.
Hope this help.
function addInputContentToParagraph() {
var txtValue1 = document.getElementById('textbox1').value;
var txtValue2 = document.getElementById('textbox2').value;
document.getElementById('para').innerHTML = txtValue1 + ' ' + txtValue2;
}
a {
cursor:pointer;
border:1px solid #333;
padding:4px;
margin:10px;
display:inline-block;
}
<form id="myForm" name="myForm">
<input type="text" name="textbox1" id="textbox1" value="1">
<input type="text" name="textbox2" id="textbox2" value="2">
</form>
<a onclick="addInputContentToParagraph();">Add Input Values to Paragraph</a>
<p id="para"></p>

incorrect radio value eventually shown.. can't figure out why

I am using some code to display radio buttons as images:
HTML:
<div id="skin_1" title="Walk">
<input type="radio" name="travel_mode" id="mode_walking" value="WALKING" /><br>
Walk
</div>
<div id="skin_2" title="Drive">
<input type="radio" name="travel_mode" id="mode_driving" value="DRIVING" /><br>
Drive
</div>
<div id="skin_3" title="Bike">
<input type="radio" name="travel_mode" id="mode_bicycle" value="BICYCLING" /><br>
Bike
</div>
<div id="skin_4" title="Transit">
<input type="radio" name="travel_mode" id="mode_transit" value="TRANSIT" /><br>
Transit
</div>
<div>
What mode is selected?
</div>
JS:
$(function () {
$('input:radio').hide().each(function () {
var label = $("label[for=" + '"' + this.id + '"' + "]").text();
$('<a ' + (label != '' ? 'title=" ' + label + ' "' : '') + ' class="radio-fx ' + this.name + '" href="#"><span class="radio' + (this.checked ? ' radio-checked' : '') + '"></span></a>').insertAfter(this);
});
$('.radio-fx').on('click', function (e) {
$check = $(this).prev('input:radio');
var unique = '.' + this.className.split(' ')[1] + ' span';
$(unique).attr('class', 'radio');
$(this).find('span').attr('class', 'radio-checked');
$check.attr('checked', true);
}).on('keydown', function (e) {
if ((e.keyCode ? e.keyCode : e.which) == 32) {
$(this).trigger('click');
}
});
});
Problem:
Eventually after changing the radio button and clicking "What mode is selected?" enough times the WRONG radio button value is alerted.
Question:
How can I get the correct value of the radio button every time?
Here is the fiddle: Live Fiddle Here
I just added one line to clear all the checkbox:
$('.radio-fx').on('click', function (e) {
$("input[name=travel_mode]").removeAttr("checked"); // add this line
.....
Full Fiddle
Define the variable inside the function so that it gets reset on each time.
function testMe() {
var selected_travel_mode = $("input[name=travel_mode]:checked").val();
alert(selected_travel_mode);
}
you have to reset radio checked state when select new one.
var pre;
$('.radio-fx').on('click', function (e) {
if(pre!==undefined)
$(pre).attr('checked',false);
pre = $(this).prev('input:radio');
$check = $(this).prev('input:radio');
var unique = '.' + this.className.split(' ')[1] + ' span';
$(unique).attr('class', 'radio');
$(this).find('span').attr('class', 'radio-checked');
$check.attr('checked', true);
}).on('keydown', function (e) {
if ((e.keyCode ? e.keyCode : e.which) == 32) {
$(this).trigger('click');
}
});
});
Try to do something like this working example:
function testMe() {
if ($("input:radio[name='travel_mode']").is(":checked")) {
alert($("input:radio[name='travel_mode']:checked").attr("value"));
// or
alert($("input:radio[name='travel_mode']:checked").val());
} else {
alert("You must make a choice!");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="skin_1" title="Walk">
<input type="radio" name="travel_mode" id="mode_walking" value="WALKING" /><br>
Walk
</div>
<div id="skin_2" title="Drive">
<input type="radio" name="travel_mode" id="mode_driving" value="DRIVING" /><br>
Drive
</div>
<div id="skin_3" title="Bike">
<input type="radio" name="travel_mode" id="mode_bicycle" value="BICYCLING" /><br>
Bike
</div>
<div id="skin_4" title="Transit">
<input type="radio" name="travel_mode" id="mode_transit" value="TRANSIT" /><br>
Transit
</div>
<div>
What mode is selected?
</div>

Save dynamically generated input fields

I am using this code to generate dynamically ADD More input fields and then plan on using Save button to save their values in database. The challenge is that on Save button, I want to keep displaying the User Generated Input fields. However they are being refreshed on Save button clicked.
javascript:
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum++;
var row = '<p id="rowNum' + rowNum + '">Item quantity: <input type="text" name="qty[]" size="4" value="' + frm.add_qty.value + '"> Item name: <input type="text" name="name[]" value="' + frm.add_name.value + '"> <input type="button" value="Remove" onclick="removeRow(' + rowNum + ');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum' + rnum).remove();
}
</script>
HTML:
<form method="post">
<div id="itemRows">Item quantity:
<input type="text" name="add_qty" size="4" />Item name:
<input type="text" name="add_name" />
<input onclick="addRow(this.form);" type="button" value="Add row" />
</div>
<p>
<button id="_save">Save by grabbing html</button>
<br>
</p>
</form>
One approach is to define a template to add it dynamically via jQuery
Template
<script type="text/html" id="form_tpl">
<div class = "control-group" >
<label class = "control-label"for = 'emp_name' > Employer Name </label>
<div class="controls">
<input type="text" name="work_emp_name[<%= element.i %>]" class="work_emp_name"
value="" />
</div>
</div>
Button click event
$("form").on("click", ".add_employer", function (e) {
e.preventDefault();
var tplData = {
i: counter
};
$("#word_exp_area").append(tpl(tplData));
counter += 1;
});
The main thing is to call e.preventDefault(); to prevent the page from reload.
You might want to check this working example
http://jsfiddle.net/hatemalimam/EpM7W/
along with what Hatem Alimam wrote,
have your form call an upate.php file, targeting an iframe of 1px.

asp.net mvc and javascript textbox issue

I have a problem with the TextBox. When I was entering duplicate data, it is not allowing. That is what exactly I need but after saving data again it is allowing the duplicate data. How can I handle the scenario?
Here is my code.
var Controls = {
saveObjectives: function (actionurl) {
var frm = $('form[name=frmObjectives]')
frm.attr('action', actionurl);
frm.submit();
},
addObjectiveCheckbox: function () {
var text = $('#txtObjective').val();
$('#txtObjective').val('');
if ($.trim(text) == '')
return;
if ($('input[type=checkbox][value="' + text + '"]').length == 0)
$('#dvObjectives').prepend('<input type="checkbox" name="chkNewobjectives" value="' + text + '" Checked /> ' + text + '<br />');
},
And my HTML code is:
<input id="btnAddObj" class="btn" type="button" onclick="Controls.addObjectiveCheckbox();" value="Add Objective"/>
</div>
<div id="dvObjectives" name="ObjectivesList">
#foreach (Andromeda.Core.Entities.Objectives objective in Model)
{
<label class="checkbox">
<input type="checkbox" name="chkobjectives" Checked value="#objective.ObjectiveID" />#objective.ObjectiveText
</label>
}
</div>
You are using value='whatever text` in the jQuery, but value='ObjectiveID' in the view. This should fix it:
<input type="checkbox" name="chkobjectives" Checked value="#objective.ObjectiveText" />#objective.ObjectiveText

Categories