Prototype: add/remove input element - javascript

I'm creating file(images) upload form.
I want to add input elements by clicking on button.
This is my input:
<input type="file" name="file"/>
I've alerady write some code:
<script language="javascript">
fields = 0;
function addInput() {
if (fields < 10) {
document.getElementById('text').innerHTML += "<input type="file" name="file"/><br />";
fields += 1;
} else {
document.getElementById('text').innerHTML += "<br />Only 10 upload fields allowed.";
document.form.add.disabled=true;
}
}
</script>
But it's ugly and not works...
I have prototype library and want to use it to add inputs.
So i need a button to add given inputs and on more button near every input to remove it - like when you attaching files to your mail.

[See it in action]
HTML
<div id="text"></div>
<div id="warning"></div>
Javascript
fields = 0;
function addInput() {
if (fields < 10) {
var id = "file" + fields;
document.getElementById('text').innerHTML +=
"<div><input type='file' name='"+id+"' />" +
" <a href='#' onclick='removeInput(this.parentNode)' />remove</div>";
fields += 1;
} else {
document.getElementById('warning').innerHTML =
"Only 10 upload fields allowed.";
document.form.add.disabled = true;
}
}
function removeInput( el ) {
if (fields > 0) {
document.getElementById('warning').innerHTML = "";
var parent = document.getElementById('text');
parent.removeChild(el);
fields -= 1;
}
}
​
​

I think problem with use of "
document.getElementById('text').innerHTML += "<input type="file" name="file"/><br />";
should be
document.getElementById('text').innerHTML += "<input type='file' name='file'/><br />";
To remove field
document.getElementById('text').innerHTML += "<div id='div_"+fields+"'><input type='file' name='file'/><br /><a onclick='removeDiv(/""+fields+"/")' href='javascript:void(0)'>Remove</a></div>";
and add javasript function
function removeDiv(val)
{
var d = document.getElementById('text');
var olddiv = document.getElementById("div_"+id);
d.removeChild(olddiv);
fields-=1; //this should be done to decrement count
}

Related

Radio button inside div

I have a form html which can add the form dynamically. I have problem with radio button, it can only select one option (even when the radio button is in different tag). I search the solution, one solution is to change the name of the radio button. Is there any other way to do it? Because my other input all use same name and when submit the form all input can be collected in an array.
If there's no other way, how can I change the name of the radio button for the cloned element?
Here's my code:
app.get('/form', function (req, res) {
var html='';
html += `<head>
<style>
.formset {
border-style: solid;
border-width: 1px;
}
</style>
<script>
var id=1
function myFunction() {
id++
var elmnt = document.getElementById("div1")
var cln = elmnt.cloneNode(true)
cln.id = "div"+id
document.getElementById("divParent").appendChild(cln);
}
</script>
</head>`;
html +="<body>";
html += "<p>Click the button to make a BUTTON element with text.</p>";
html += '<button onclick="myFunction()">Add form</button>';
html += "<form action='/thank' method='post' name='form1'>";
html += "<div id='divParent'>";
html += "<div id='div1' name='formset' class='formset'>";
html += "<p>Name: <input type= 'text' name='name'></p>";
html += "<p>Sex: Male <input type='radio' name='gender' value='male'>"
html += " Female <input type='radio' name='gender' value='female'></p>"
html += "<p>Email: <input type='text' name='email'></p>";
html += "<p>Address:<input type='text' name='address'></p>";
html += "<p>Mobile number:<input type='text' name='mobilno'></p>";
html += "</div>";
html += "</div>";
html += "<input id='input1' type='submit' value='submit'>";
html += "<INPUT type='reset' value='reset'>";
html += "</form>";
html += "</body>";
res.send(html);
});
And the code to handle the form:
app.post('/thank', urlencodedParser, function (req, res){
var reply='';
reply += "<br>Array length is : " + req.body.name.length;
reply += "<br>Your name is : " + req.body.name;
reply += "<br>Sex is : " + req.body.gender;
reply += "<br>Your E-mail id is : " + req.body.email;
reply += "<br>Your address is : " + req.body.address;
reply += "<br>Your mobile number is : " + req.body.mobilno;
res.send(reply);
});
I think you need change name of the radio input, add class to radio to make it can be found by getElementsByClassName.
html += "<p>Sex: Male <input type='radio' class='gender' name='gender' value='male'>"
html += " Female <input type='radio' class='gender' name='gender' value='female'></p>"
//change the name, add id to the end
function changeName(element, id) {
var x = element.getElementsByClassName("gender");
var i;
for (i = 0; i < x.length; i++) {
x[i].name += id;
}
}
function myFunction() {
id++
var elmnt = document.getElementById("div1")
var cln = elmnt.cloneNode(true)
cln.id = "div"+id
//change radio id
changeName(cln, id);
document.getElementById("divParent").appendChild(cln);
}

Javascript remove text input dynamically

Hi i have the following code..where we can add text input dynamically
what i would like to do is add text input and option to remove text input except the default first one
the add text input is working but not the remove text input
https://jsfiddle.net/ob8n48cg/20/
<script>
var counter = 1;
var limit = 3;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
function removeInput(divName){
var newdiv = document.removeElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).removeChild(newdiv);
}
</script>
<form method="POST">
<div id="dynamicInput">
Entry 1<br><input type="text" name="myInputs[]">
</div>
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');">
<button onclick="removeInput('dynamicInput');">Remove Input</button>
</form>
Try this
var counter = 1;
var limit = 3;
function addInput(divName){
if (counter === limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
function removeInput(event,divName){
event.preventDefault()
var parent = document.getElementById(divName)
parent.removeChild(parent.lastElementChild)
counter--
}
<form>
<div id="dynamicInput">
<div>
Entry 1<br><input type="text" name="myInputs[]">
</div>
</div>
<input type="button" value="Add another text input" onclick="addInput('dynamicInput');">
<button onclick="removeInput(event,'dynamicInput');">Remove Input</button>
</form>
When you run your code, make sure to check the console window in the browser, checking that shows you have an error in your removeInput function:
(index):75 Uncaught ReferenceError: newdiv is not defined
at removeInput ((index):75)
at HTMLButtonElement.onclick ((index):87)
removeInput # (index):75
onclick # (index):87
Make sure to define newdiv in the remove function as well as the add function!

Javascript wrong variable type

Hello I'm preparing little guessing word game.
Somehow the type of my variable get changed from string to obj type what causes an Uncaught TypeError.
Here is a fragment of code:
let passwordArray = ["Java Script Developer", "FrontEnd"];
let sample = passwordArray[Math.floor((Math.random() *
passwordArray.length))];
let password = sample.toUpperCase();
let new_password = "";
for(let x =0; x<password.length;x++){
if(password[x]===" "){new_password += " "}
else{new_password += "-"}
}
$("#password span").text(new_password);
This part works correclty problem appears when I want to repalce a letter
String.prototype.replaceAt = function(index, replacement){
return this.substr(0,index) + replacement + this.substr(index + replacement.length)
};
function check(num) {
let test = false;
let temp = $(event.target).val();
if(password.indexOf(temp)>-1){test=true; /*alert(test +"/"+temp+"/"+password)*/}
$("#"+num).attr("disabled", true);
if(test === true) {
$("#"+num).removeClass("letter").addClass("hitletter");
let indeksy =[];
for(let i =0; i<password.length;i++ ){
if(password.charAt(i) === temp){indeksy.push(i)}
}
for(let x=0; x<indeksy.length;x++) {
let indx = indeksy[x];
new_password = new_password.replaceAt(indx, temp);
}
$("#password").html(new_password);
}};
My HTML basically is just:
<nav>
<input type="button" value="o mnie" id="me">
<input type="button" value="kalkulator" id="cal">
<input type="button" value="Wisielec" id="wis">
<input type="button" value="Memory" id="mem">
</nav>
<div id="content"></div>
Rest is dynamically added in JS:
$(function() {
$("#wis").click(function () {
$("#content").empty().append("" +
"<div id='container'>\n" +
"<div id='password'><span>Sample text</span></span></div>\n" +
"<div id='counter'>Counter: <span id='result'></span></div>\n" +
"<div id='gibbet' class='image'></div>\n" +
"<div id='alphabet'></div>\n" +
"<div id='new'>\n" +
"<input type='text' id='new_password'/>\n" +
"<button id='add' onclick='newPass()'>Submit</button>\n" +
"</div>\n" +
"</div>"
);
start();
});
});
function start(){
let new_password = "";
$("#contetn").empty();
let letters = "";
for(let i=0; i<32; i++){
letters += "<input class='letter' type='button' value='"+litery[i]+"' onclick='check("+i+")' id='"+i+"'/>"
}
$("#alphabet").html(letters);
$("#result").text(mistakeCounter);
for(let x =0; x<password.length;x++){
if(password[x]===" "){new_password += " "}
else{new_password += "-"}
}
$("#password span").text(new_password);
}
The problem is that variable new_password is somehow changing from type string to type object when i want to use function replaceAt()
looking at your code, with the new String.prototype.replaceAt this error can happen on 2 situations:
when the variable that uses replaceAt is not a string, example:
null.replaceAt(someIndex,'someText');
{}.replaceAt(someIndex,'someText');
[].replaceAt(someIndex,'someText');
the other situation is when you pass null or undefined as replacement:
"".replaceAt(someIndex,undefined);
"".replaceAt(someIndex,null);
just add some verification code and should be working good

Display the checkboxes selected into a section and the unselected into another one

I want to show the checkboxes selected into a div but actually I have a duplicate item in the list and I'm not sure how to display the unselected items into another div.
You can try out here http://jsfiddle.net/tedjimenez/7wzR5/
Here my code:
JS CODE
/* Array */
var list = new Array("valuetext000", "valuetext001", "valuetext002", "valuetext003", "valuetext004", "valuetext005", "valuetext006", "valuetext007", "valuetext008", "valuetext009", "valuetext010", "valuetext011", "valuetext012", "valuetext013", "valuetext014", "valuetext015", "valuetext016", "valuetext017")
var html = "";
/* Array will be converted to an ul list */
for (var i = 0; i < list.length; i++) {
html += "<input type='checkbox' name='boxvalue' value='" + list[i] + "' /><label>" + list[i] + "</label><br>";
}
$("#elmAv").append(html);
THE HTML CODE
<form>
<div id="elmAv"></div>
<div id="selectionResult"></div>
<script>
/* Function to display the items selected */
function showBoxes(frm) {
var checkedItems = "\n";
//For each checkbox see if it has been checked, record the value.
for (i = 0; i < frm.boxvalue.length; i++) {
if (frm.boxvalue[i].checked) {
checkedItems = checkedItems + "<li>" + frm.boxvalue[i].value + "<li>";
}
}
$("#elmAv").empty();
$("#selectionResult").append(checkedItems);
}
</script>
<input type="Button" value="Get Selection" onClick="showBoxes(this.form)" />
</form>
Simply add another div after selectionResult like this:
<div id="unselectedResult"></div>
And then update showBoxes() with the following code:
function showBoxes(frm) {
var checkedItems = "Checked:<br>\n";
var uncheckedItems = "Unchecked:<br>\n";
//For each checkbox see if it has been checked, record the value.
for (i = 0; i < frm.boxvalue.length; i++) {
if (frm.boxvalue[i].checked) {
checkedItems = checkedItems + "<li>" + frm.boxvalue[i].value + "</li>";
}
else {
uncheckedItems = uncheckedItems + "<li>" + frm.boxvalue[i].value + "</li>";
}
}
$("#elmAv").empty();
$("#selectionResult").append(checkedItems);
$('#unselectedResult').append(uncheckedItems);
}
Should get the result you're looking for.
This should work. Added another array listChecked to track checked values.
<script>
/* Array */
var list = new Array("valuetext000", "valuetext001", "valuetext002", "valuetext003", "valuetext004", "valuetext005", "valuetext006", "valuetext007", "valuetext008", "valuetext009", "valuetext010", "valuetext011", "valuetext012", "valuetext013", "valuetext014", "valuetext015", "valuetext016", "valuetext017")
var listChecked = new Array();
$(document).ready(function() {
displayUnchecked();
});
/* Array will be converted to an ul list */
function displayUnchecked()
{
var html = "";
for (var i = 0; i < list.length; i++) {
if ($.inArray(list[i], listChecked) == -1)
html += "<input type='checkbox' name='boxvalue' value='" + list[i] + "' /><label>" + list[i] + "</label><br>";
}
$("#elmAv").html(html);
}
</script>
</head>
<body>
<form>
<div id="elmAv"></div>
<div id="selectionResult"></div>
<script>
/* Display the items selected */
function showBoxes(frm) {
var checkedItems = "\n";
//alert('here');
//For each checkbox see if it has been checked, record the value.
for (i = 0; i < frm.boxvalue.length; i++) {
if (frm.boxvalue[i].checked) {
listChecked.push(frm.boxvalue[i].value);
}
}
$.each(listChecked, function (index, value)
{
checkedItems = checkedItems + "<li>" + value + "</li>";
});
//alert('here');
displayUnchecked();
//$("#elmAv").empty();
$("#selectionResult").html(checkedItems);
}
</script>
<input type="Button" value="Get Selection" onClick="showBoxes(this.form)" />
</form>
</body>

How do I define a variable and call it in a hidden input field?

I have a javascript code that does some math and I need to be able to just pull the final result and include it in a form. To do that I wanted to just use a <input type="hidden" name="new total">. I want to grab the results from the field "New Total". You can see my javascript code in action here. http://jsfiddle.net/danielrbuchanan/yjrTZ/5/
var prices = [];
function remove(arr,itm){
var indx = arr.indexOf(itm);
if (indx !== -1){
arr.splice(indx,1);
}
}
function calculateSectedDues(checkbox, amount) {
if (checkbox.checked === true) {
prices.push(amount);
} else {
remove(prices, amount);
}
var total = 0;
for (var i = 0, len = prices.length; i < len; i++)
total += prices[i];
var min = prices.slice().sort(function(a,b){return a-b})[0];
if(typeof min === 'undefined') min = 0;
var withDiscount = total - min;
var discountAmount = withDiscount - total;
//document.grad_enroll_form.total.value = total;
document.querySelector("#value").innerHTML = "Total: $"+total+'<br>';
document.querySelector("#value").innerHTML += "Discount: $"+discountAmount+'<br>';
document.querySelector("#value").innerHTML += "New total: $"+withDiscount+'<br>';
}
It seems simple, for some reason I'm drawing a blank on how to do it.
What i think you want is to set an input value with your variable, so i think it should go like this:
Javascript:
document.getElementById("newTotal").value = your_new_total;
HTML:
<form>
<input id='newTotal' type='hidden' name='NewTotal' value='' />
</form>
Hope this helps.
<input type="hidden" id="new_total" name="new_total">
<!-- no spaces in name and id -->
Put this code at end of the calculateSectedDues function
document.getElementById('new_total').value = withDiscount
You have a couple of options.
Option 1:
jQuery
Add a visible div, how ever you want to do things.
Bind onChange() events to your input fields that drive the calculation.
<div id="finalValue"></div>
<script language="javascript">
$(function() {
$("form input").change(function() {
calculateSectedDues($("#checkboxid"), $("#amountid").val());
});
});
</script>
In the calculateSectedDues() function add this to the end:
$("#finalValue").html("Total: $" + total + "<br />Discount: " + discountAmount + "<br />New Total: " + withDiscount + "<br />");
Option 2:
No jQuery
<div id="finalValue"></div>
<script language="javascript">
function bindEvent() {
calculateSectedDues(document.getElementById("checkboxid"), document.getElementById("amountid").value);
}
window.onload = function()
{
var elJ = document.getElementsByTagName("input");
for (var i=0;i<elJ.length;i++) {
elJ[i].addEventListener('change',bindEvent,false);
}
}
</script>
In the calculateSectedDues() function add this to the end:
document.getElementById("finalValue").InnerHtml("Total: $" + total + "<br />Discount: " + discountAmount + "<br />New Total: " + withDiscount + "<br />");
Is that what you are trying to get after?
You should also remember to do the calculation on the Server Side too and not rely on the JavaScript to do it for you. This would simply be to notify the user what they are getting before hand. Otherwise, front-end hacks could easily be done if you are using a hidden total field.

Categories

Resources