I'm trying to move div elements of a dynamic form up or down:
Here is my form:
<form name="f_form">
Order name <input type="text" name="ord" id="order" />
<div id="fields">
<div id="hid1"><a href="#" id="did1">
<img src="d.jpg" /></a><a href="#" id="uid1">
<img src="u.jpg" /></a><input type="text" name="p_name[]" id="names" />
<input type="text" name="quant[]" id="quant" size="3" />
<input type="text" name="pr[]" id="price" size="10" />
<input type="text" name="sum_a" id="sum" size="10" disabled="disabled"/>
</div>
<input type="button" name="nauj" id="nau" value="Add item"/><br />
</div>
</form>
When I click "add item" button JS is called:
$("#nau").click(function () {
(newdiv = document.createElement('div')).id = "hid"+ (counter + 1) +"";
newdiv.innerHTML = '<img src="d.jpg" /><img src="u.jpg" /><input type="text" name="p_name[]" id="names" />
<input type="text" name="quant[]" id="quant" size="3" />
<input type="text" name="pr[]" id="price" size="10" />
<input type="text" name="sum_a" id="sum" size="10" disabled="disabled"/>X';
document.getElementById('fields').appendChild(newdiv);
counter++;
});
Each form fields row has two arrow (up and down) images: <img src="d.jpg" /><img src="u.jpg" />
when I click on arrow I need to move all row of form fields up or down (move <DIV id=hid..>) tried like this but it didint worked.. (move up function)
$("a[id^='uid']").on('click', function() {
var numrow = $(this).attr("id");
numrow = numrow.substr(3);
var nr = 1;
sumrow = numrow - nr;
var eil = 'id=' + numrow;
numrowas = "#hid"+numrow;
srowas = "#hid"+sumrow;
$(numrowas).before($(srowas));
});
Thanks for advices.
Same sort of solution as #WTK, using .prev(), but different approach. And oh, I couldn't resist and did some cleanup ;)
See http://jsfiddle.net/WmbmF/4/
First of all you're not using on() correctly - the event handler isn't binded as you would expect. The correct syntax would be:
// "watch for" elements matching selector "a[id^='did']" created inside #fields
$("#fields").on('click', "a[id^='did']", function(e) {...})
Second of all, you are trying to operate on id attributes to deremine after/before what div to append your current element. That's messy, a cleaner approach is using .next() and .prev() to determine what is the next or previous node in relation to the clicked one.
I've created a fiddle as an example: http://jsfiddle.net/SPgax/22/
Just as a side note: your code is messy, I didn't act on it because it's beyond scope of your question. No offence :)
Related
Requirements:
A new text box should appear with a delete button at closing after clicking '+Add Stop'.
If a delete(x) button is clicked, the respective text box should be removed and Stop #(sequence numbering) should be changed as well.
Need help on:
I have tried to achieve the both above requirements. I get results for #1. But for #2, After adding more items, the delete button works/removes only the last added item only but it should work the same for all items.
Stop # sequence number should be maintained after the removal of an item(s). I need help with this logic also.
HTML:
<form action="https://www.example.com" method="POST">
<label for="stype">Service Type:</label>
<select id="stype" name="service-type">
<option disabled="disabled" selected="selected">Choose Service</option>
<option value="From Airport">From Airport</option>
<option value="To Airport">To Airport</option>
</select><br/><br/>
<label for="fullname">Name: </label><input id="fullname" name="name" size="20" type="text" maxlength="20" placeholder="John Doe" required /><br/><br/>
<label for="phone">Phone: </label><input id="phone" name="phone" maxlength="12" type="tel" placeholder="012-345-6789" required /><br/><br/>
<label for="email">Email: </label><input id="email" name="email" size="30" type="email" maxlength="30" placeholder="contact#example.com" required /><br/><br/>
<label for="ptime">Pickup time </label><input id="ptime" name="pickup-time" type="time" required /><br/><br/>
<label for="pdate">Pickup Date </label><input id="pdate" name="pickup-date" type="date" required /><br/><br/>
<div id="add_stop_here">
</div>
<input type="button" id="add" value="+Add Stop" onclick="test();" />
</form>
JavaScript:
var counter = 0;
function test () {
counter += 1;
var addHtml = '\
<div class="input-box">\
<label for="stop'+counter+'">Stop '+counter+':</label>\
<input type="text" id="stop'+counter+'" name="stop"/ > <a id="rmv'+counter+'" class="remove_stop" href="#">x</a>\
</div>';
var add_hre = document.getElementById("add_stop_here");
add_hre.innerHTML += addHtml;
document.querySelector("#rmv"+counter)
.addEventListener('click', function(){
var removeEl = this.parentNode;
add_hre.removeChild(removeEl);
});
}
Some issues to take care of:
To make this work, I would refrain from using id attributes that have a sequential number. It is not best practice.
Instead, in order to link a label element with its input element, make the input element a child of the corresponding label element. Now the id and for attributes are no longer needed.
Don't use innerHTML += as that will reset the values of the inputs that are already in the document, and will remove the event listeners. Instead use insertAdjacentHTML.
To keep the numbering in pace, use a span element that only has that number, and renumber all those span elements after every change. You can also use it after an insert, just to keep the code clean, and avoid that you need to maintain a counter.
To avoid that you need to attach a new event handler for every new element, listen to click events on the container element, and then check in that single handler which element was clicked. This is called event delegation.
Don't name your function test. Give it a useful name, like insertBusStop.
Instead of binding that handler via HTML attribute, bind it via code.
For multi-line strings you can use back tick delimiters (template literals)
I'd suggest that after clicking the Add button, the focus is put on the newly created input element. This facilitates the input procedure for the user.
Here is how that would work:
var add_hre = document.getElementById("add_stop_here");
document.getElementById("add").addEventListener("click", addBusStop);
function addBusStop() {
var addHtml = `
<div class="input-box">
<label>
Stop <span class="stop_number"></span>
<input type="text" name="stop"/> <a class="remove_stop" href="#">x</a>
</label>
</div>`;
add_hre.insertAdjacentHTML("beforeend", addHtml);
renumber();
add_hre.querySelector(".input-box:last-child input").focus();
}
function renumber() {
let i = 1;
for (let labelSpan of add_hre.querySelectorAll(".stop_number")) {
labelSpan.textContent = i++;
}
}
// Use event delegation
add_hre.addEventListener('click', function(e) {
if (!e.target.classList.contains("remove_stop")) return;
var removeEl = e.target.parentNode.parentNode; // need one more level now
add_hre.removeChild(removeEl);
renumber();
});
<div id="add_stop_here"></div>
<input type="button" id="add" value="+Add Stop"/>
You can do this with each() and find() function easily.
var counter = 0;
$("#add").click(function () {
counter++;
$("#add_stop_here").append(
'<div class="input-box"><label for="stop' +
counter +
'">Stop' +
counter +
': <input type="text" id="stop' +
counter +
'" name="stop"/ ></label> <a id="rmv' +
counter +
'" class="remove_stop" href="#">X</a></div>'
);
});
$(document).on("click", ".remove_stop", function () {
$(this).closest("div").remove(); //use closest here
$("#add_stop_here .input-box").each(function (index) {
$(this)
.find("label:eq(0)")
.attr("id", "stop" + (index + 1));
$(this)
.find("label:eq(0)")
.html("Stop" + (index + 1) + '<input type="text" name="stop" />');
});
counter--;
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<form action="https://www.example.com" method="POST">
<label for="stype">Service Type:</label>
<select id="stype" name="service-type">
<option disabled="disabled" selected="selected">Choose Service</option>
<option value="From Airport">From Airport</option>
<option value="To Airport">To Airport</option></select
><br /><br />
<label for="fullname">Name: </label
><input
id="fullname"
name="name"
size="20"
type="text"
maxlength="20"
placeholder="John Doe"
required
/><br /><br />
<label for="phone">Phone: </label
><input
id="phone"
name="phone"
maxlength="12"
type="tel"
placeholder="012-345-6789"
required
/><br /><br />
<label for="email">Email: </label
><input
id="email"
name="email"
size="30"
type="email"
maxlength="30"
placeholder="contact#example.com"
required
/><br /><br />
<label for="ptime">Pickup time </label
><input id="ptime" name="pickup-time" type="time" required /><br /><br />
<label for="pdate">Pickup Date </label
><input id="pdate" name="pickup-date" type="date" required /><br /><br />
<div id="add_stop_here"></div>
<input type="button" id="add" value="+Add Stop" />
</form>
I have 2 textboxes with a type="number".
1 textbox is my 'master' textbox, then I have another subsequent textbox that I would like that IF the 'master' textbox is filled in with a number, the subsequent textbox would get the same value.
I thought about using the data- attribute but I am not sure how to target if the 'master' textbox is filled then, then subsequently put the same value in the sub textbox(es) with the same data- attribute.
In my example below I also use spans to create plus and minus buttons that adjust the value based on the value. This is in the JS section.
My current HTML is as follow:
<div id="masterTextboxes">
<span class="minusBtn AddMinusButton">-</span>
<input type="number" value="" placeholder="0" data-attendees="Adult" />
<span class="addBtn AddMinusButton">+</span>
<span class="minusBtn AddMinusButton">-</span>
<input type="number" value="" placeholder="0" data-attendees="Child" />
<span class="addBtn AddMinusButton">+</span>
</div>
<!--Values from Master Textboxes should populate into these textboxes as well.-->
<div id="subTextboxes">
<span class="minusBtn AddMinusButton">-</span>
<input type="number" value="" placeholder="0" data-attendees="Adult" />
<span class="addBtn AddMinusButton">+</span>
<span class="minusBtn AddMinusButton">-</span>
<input type="number" value="" placeholder="0" data-attendees="Child" />
<span class="addBtn AddMinusButton">+</span>
</div>
Javascript
<script>
$(document).ready(function () {
/*Add an minus buttons for variants*/
$(".AddMinusButton").on('click touchstart', function (event) {
event.preventDefault();
//Add button active style for touch.
var $button = $(this);
var oldValue = $button.parent().find("input").val();
var newVal = oldValue;
//Hide .decButton for oldValue
if (newVal == 0 || oldValue == 0 ) {
oldValue = 0;
}
else { $button.parent().find(".minusBtn").show(); }
if ($button.text() == "+") {
newVal = parseFloat(oldValue) + 1;
// Don't allow decrementing below zero
if (oldValue >= 1) {
newVal = parseFloat(oldValue) - 1;
}
}
$button.parent().find("input.attendeeQuantityInput").val(newVal);
//Sub textboxes should take value of master textboxes. Is this correct syntax?
//This is probably wrong.
$('#subTextboxes input').data("attendee").val(newVal);
});//End button click
});
</script>
I hope this makes sense on what I am trying to get out of this.
Thanks in advance.
I would like that IF the 'master' textbox is filled in with a number,
the subsequent textbox would get the same value.
You can do it like this:
<p>
<label>Master 1: <input type="number" id="master1" placeholder="0" /></label><br>
<label>Dependant 1: <input type="number" class="dependant1" placeholder="0" /></label>
</p>
<p>
<label>Master 2: <input type="number" id="master2" placeholder="0" /></label><br>
<label>Dependant 2: <input type="number" class="dependant2" placeholder="0" /></label><br>
<label>Dependant 2: <input type="number" class="dependant2" placeholder="0" /></label>
</p>
And in the JS:
$("input[id^='master']").on("change", function(){
var no = this.id.replace("master", "");
var selector = ".dependant" + no
$(selector).val(this.value);
});
This makes use of jQuery's attribute starts with selector and will work for any number of inputs provided the class names match.
Demo
You could do this:
HTML:
<div id="masterTextboxes">
<p>Master</p>
<input type="number" value="" placeholder="0" data-attendees="Adult" />
<input type="number" value="" placeholder="0" data-attendees="Child" />
</div>
<div id="subTextboxes">
<p>Sub</p>
<input type="number" value="" placeholder="0" data-attendees="Adult" />
<input type="number" value="" placeholder="0" data-attendees="Child" />
</div>
JS:
// On change in master inputs...
$("#masterTextboxes input", this).on("change", function() {
// Store Master inputs in master variable and Sub inputs in sub variable.
var master = $("#masterTextboxes input"),
sub = $("#subTextboxes input");
// Match master and sub values by using the master array key as reference.
$(sub[$.inArray($(this)[0], master)]).val( $(this).val() );
});
The jQuery code relies on the condition that the Sub inputs follow the same order as the Master's inside each respective div.
JSFiddle:
Here's a working JSFiddle for reference.
The problem: I have a page with many <input> fields (just say all are text fields)
I would like to have a button, when click on it, all input fields will become plaintext only.
e.g. <input type="text" value="123" /> becomes 123
and if I click on another button, the text will change back to
e.g. 123 becomes <input type="text" value="123" />
Is there an automatic way to scan for all the <input>s and change them all at once using javascript and jquery.
Thank you!
Edited
Seems you guys are getting the wrong idea.
Read what I have written again: e.g. <input type="text" value="123" /> becomes 123
I have value="123" already, why would I want to set the value again???
What I want is e.g.
<body><input type="text" value="123" /><input type="text" value="456" /></body> becomes <body>123456</body> and later <body>123456</body> back to <body><input type="text" value="123" /><input type="text" value="456" /></body>
Use this to go one way,
$('input').replaceWith(function(){
return $('<div />').text(this.value).addClass('plain-text');
});
and this to go the other.
$('.plain-text').replaceWith(function(){
return $('<input />').val($(this).text());
});
Check this link http://jsfiddle.net/Evmkf/2/
HTML:
<div id='divInput'>
<input type="text" value='123' />
<br/>
<input type="text" value='456' />
<br/>
<input type="text" value='789' />
</div>
<div id='plainText' style='display:none'></div>
<div>
<input type="button" id='btnPlain' value='Make It Plain' />
<input type="button" id='btnInput' value='Make It Text' />
</div>
Javascript:
$("#btnPlain").bind('click',function(){
$("#plainText").html('');
$("#divInput input[type=text]").each(function(index){
$("#plainText").append('<span>'+$(this).val()+'</span>');
$("#divInput").hide();
$("#plainText").show();
});
});
$("#btnInput").bind('click',function(){
$("#divInput").html('');
$("#plainText span").each(function(index){
$("#divInput").append('<input type="text" value="'+$(this).text()+'"/><br/>');
$("#plainText").hide();
$("#divInput").show();
});
});
Try this FIDDLE
$(function() {
var arr = [];
$('#btn').on('click', function() {
var $text = $('#inp input[type="text"]');
if( $text.length > 0){
$text.each(function(i) {
arr[i] = this.value;
});
$('#inp').html(arr.join());
}
else{
if(arr.length <= 0){
}
else{ // Add Inputs here
var html = '';
$.each(arr, function(i){
html += '<input type="text" value="' + arr[i]+ '"/>'
});
$('#inp').html(html);
}
}
});
});
You need to create a hidden element for each input, then use jquery to hide the input, show the hidden element and give it the inputs value.
<input type="text" value="123" id="input_1" />
<div id="div_1" style="display:none;"></div>
$("#div_1").html($("input_1").val());
$("#input_1").hide();
$("#div_1").show();
Since input tags aren't supposed to have closing tags, is there a simple way to extract the text/HTML in between a series of input tags? For example, for the below I want to retrieve <b>Bob and Tim</b><br>Tim <i>after</i> Bob<br>.
<div id="inputs">
<input type="text" value="bob" size="4" />
<b>Bob and Tim</b><br>
<input type="text" value="tim" size="4" />
Tim <i>after</i> Bob<br>
<input type="button" value="get textbox values" id="mybutton" />
</div>
http://jsfiddle.net/gLEZd/5/
I can get the textbox's values, but how do I accomplish the above?
With a minor markup change you can do it easily,
HTML:
<div id="inputs">
<input type="text" value="bob" id="bob" size="4" />
<label for="bob"><b>Bob and Tim</b><br></label>
<input type="text" value="tim" id="tim" size="4" />
<label for="tim">Tim <i>after</i> Bob<br></label>
<input type="button" value="get textbox values" id="mybutton" />
</div>
JS:
$("#mybutton").click( function() {
$.each($('input[type="text"]'), function() {
alert($('label[for=' + this.id + ']').text());
});
});
DEMO
Incase if you don't like label tags, then simply wrap the contents inside a span like below,
<div id="inputs">
<input type="text" value="bob" id="bob" size="4" />
<span><b>Bob and Tim</b><br></span>
<input type="text" value="tim" id="tim" size="4" />
<span>Tim <i>after</i> Bob<br></span>
<input type="button" value="get textbox values" id="mybutton" />
</div>
And in JS,
$("#mybutton").click( function() {
$.each($('input[type="text"]'), function() {
alert($(this).next().text());
});
});
DEMO
already more or less available in the fiddle and stated in the comment. but here also the code for the others directly with a small explanation:
$("#mybutton").click( function() {
var tempContainer = $("#inputs").clone();
tempContainer.find("input").remove();
alert(tempContainer[0].innerHTML);
});
this way the container is cloned and then the inputs get removed from the cloned container... in the end we have an innerHTML without the inputs
Not sure if this is desirable, but you can strip down to text like this:
alert ( $('#inputs').unwrap().text() );
This will also strip your <b></b> and other tags though.
$("#mybutton").click( function() {
var x = $('div#inputs :not(:input)');
$.each(x, function() {
console.log(this.innerHTML);
});
});
UPDATE
$("#mybutton").click( function() {
var x = $('div#inputs :not(:input)').filter(function() {
return this.toString();
});
console.log(x); // x is the array of DOM Object
});
Ideally, if the information is linked to the input element, you should be using <label for="">. Then you could easily access the value which is associated:
<div id="inputs">
<input id="input1" type="text" value="bob" size="4" />
<label for="input1"><b>Bob and Tim</b><br></label>
<input id="input2" type="text" value="tim" size="4" />
<label for="input2 ">Tim <i>after</i> Bob<br></label>
<input type="button" value="get textbox values" id="mybutton" />
</div>
Either:
$("#mybutton").click( function() {
$.each($('input[type="text"]'), function() {
alert($(this).next('label').text());
});
});
Or:
$("#mybutton").click( function() {
$.each($('input[type="text"]'), function() {
alert($('label[for='+this.id+']').text());
});
});
I'm trying to set the value of three different input text fields with an onclick function.
I have an image that has this code...
<img src="images/delete_row.png" width="25" onClick="clearRow(0);" />
And I have three input text fields that all have the id of "0".
When I click my image I want to set the value of all three fields to empty.
Can someone please help me write a function that can do this?
Thanks!
First, you need your id values to be different. You should never have the same ID twice on the same page. So lets use this as the example HTML:
<input type="text" id="name_0" name="name" />
<input type="text" id="phone_0" name="phone" />
<input type="text" id="email_0" name="email" />
You could use this JavaScript function:
<script type='text/javascript'>
function clearRow(id){
var name = document.getElementById('name_' + id),
phone = document.getElementById('phone_' + id),
email = document.getElementById('email_' + id);
// Clear values
name.value = phone.value = email.value = "";
}
</script>
And your img tag would remain unchanged:
<img src="images/delete_row.png" width="25" onClick="clearRow(0);" />
I have three input text fields that
all have the id of "0".
This is entirely wrong. In a document you can't have element with the same id. Either use a name or a classname for these textfields and make their ids different.
<script type="text/javascript">
function Change()
{
var elems = document.getElementsByName ( "myfields");
for ( var i = 0;i < elems.length; i++)
{
elems[i].value = "";
}
}
</script>
<input name="myfields" type="text" id="txt1" />
<input name="myfields" type="text" id="txt2" />
<input name="myfields" type="text" id="txt3" />
<img onclick="Change();" alt="test" src="yourimagpath" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#pic').click(function() {
alert('Clicked on pic - resetting fields')
$('.field').val('')
})
}
</script>
<img id="pic" src="image.png">
<input class="field" value="1">
<input class="field" value="2">
<input class="field" value="4">
<input class="field" value="5">
<input class="field" value="6">
<input class="field" value="7">
<input class="field" value="8">
<input class="field" value="9">
<input class="field" value="10">