Repeat a div with javascript? - javascript

I am not sure how to phrase what I'm asking (or I would probably be able to find it). What is it called when you have an indefinite number of items to add to a webpage form for submission to a db? For example, if you have a resume web site, and you want to add experience. You may have a slot for one job, and an "Add more experience" to that. What is that called? How do you implement that (js, html, css)?
EDIT:
Thanks for the comments. This is called: dynamically add form elements.

this is a basic idea ,,
http://jsfiddle.net/3mebW/
var noOfFields = 2;
$('#addNew').on('click', function(e) {
e.preventDefault();
var newField = '<br><label for="experience'+noOfFields+'">experience'+noOfFields+'</label>';
newField += '<input type="text" name="experience'+noOfFields+'"class="field"/>';
$('.field:last').after(newField);
//adding a hidden input inside the form to know the number of inserted fields
//make sure that the input is not already here
//then adding it to handle the number of inputs later
if($('#noOfFields').length === 0){
$('#Frm').append('<input type="hidden" value="2" id="noOfFields"/>');
}else{
$('#noOfFields').attr('value',noOfFields);
}
noOfFields++;
});
you can also detect the number of fields using a class or any other method

You can do this using the jQuery function .clone().
Here's the jQuery doc about it : http://api.jquery.com/clone/
You can copy your Experience input field, and set its properties (ID, name, etc) before appending it where you want.

lots of ways to do this, here is is one
http://jsfiddle.net/uuKM8/
$('#myBtn').click(function(){
$( "#myInput" ).clone().appendTo('body');
});

Related

How to get value from selected input field (not using id)

I try to do simple code for guessing notes by ear. I have tabs with several empty input fields and you need to put right numbers in these fields according to certain melody (for guitar fretboard) . One button shows first note, another button checks whether you put right or wrong number and depend on it approves or erase your number.
I know how to check every input field using its id's but can i do it such way that when i push 2nd button it get value from selected input and compare it to its placeholder or value attribute?
It is my codepen
https://codepen.io/fukenist/pen/BxJRwW
Script part
function showfirst() {
document.getElementById("fst").value = "12"
}
function show1other() {
var snote = document.getElementById("scnd").value;
if (snote == 9 ){
document.getElementById("scnd").value = "9";
}
else {
document.getElementById("scnd").value = "";
}
}
You can use document.querySelectorAll() to get all your inputs and loop over them.
Sample:
// Get all inputs as an array (actually NodeList, to be precise; but it behaves similar to an array for this use case)
var inputs = document.querySelectorAll('input');
// Function to reveal the first input's value
function showFirst(){
inputs[0].value = inputs[0].dataset.v;
}
// Function to check all values and clear input if wrong
function checkAll(){
inputs.forEach(function(input){
if(input.dataset.v !== input.value){
// Wrong answer, clear input
input.value = '';
}
});
}
<input data-v="12" size="2" value=""/>
<input data-v="9" size="2" value=""/>
<input data-v="8" size="2" value=""/>
<br/>
<button onclick="showFirst()">Show First</button>
<button onclick="checkAll()">Check All</button>
Notes:
I have used data-v to store the correct answer instead of placeholder as that attribute has a semantically different meaning
It may be out of turn but my two cents: Writing out entire songs like this by hand may become tedious. Consider using a JSON string or something similar to map out the tabs and use a templating framework to align them.. Some things you may need to look out for while designing something like this : Alignment of notes (successive notes, simultaneous notes), timing of the song, special moves like slide, hammer on etc.
It may be a better idea to make the Guitar Strings be a background element (either as a background-image or as absolutely positioned overlapping divs) (so You don't have to worry about the lines going out of alignment)
Reference:
HTMLElement.dataset
document.querySelectorAll

Change Text Field Once Drop Down Has Been Selected (Multiple forms on 1 page)

I'm looking to change the value of a <p> tag once an option from a drop down has been selected. I have that working but my issue is I am going to have lots of forms on one page and feel like I am repeating my code. Is there a way to do this with a function for example? To save me writing a new section of javascript everytime a form gets added to my page?
My javascript code:
$('.orderProduct select#packageOption').change(function(){
$('#packagePrice').html($(this).val());
});
$('.orderProduct2 select#packageOption').change(function(){
$('#packagePrice2').html($(this).val());
});
Thanks.
Add a data-element-id attribute to each select like:
<select data-element-id="packagePrice">...</select>
<select data-element-id="packagePrice2">...</select>
then you simply need this jQuery code:
$('select[data-element-id]').change(function(){
var $this = $(this);
var id = $this.data('element-id');
$('#' + id).html($this.val());
});
If you want to avoid the extra attribute you could use jQuery's DOM traversing functions, to locate which p you should update.

Dynamically give different names to fields so I can email them separately

Here's my setup so far: Fiddle
Whenever I click on the "Submit" button I need it to send an email to that specific person/email address.
But they all have the same names because I just cloned them. How do I dynamically give fields unique names and/or classes so I can email them separately?
$('.sub_container').first().clone(true).appendTo('.container').find('input').val('');
Also, since I will be dynamically adding new persons/email addresses, this must all happen on the same page. So I was thinking of using json or ajax perhaps?
Thanks in advance!
Fiddle
You can try some thign like this
Add Hidden field for counter
<input type='hidden' id='counter' value ='0' />
changes to click event
$('.add_new').click(function (e) {
var count = parseInt($("#counter").val(),10);
$("#counter").val(count+1);
var cloneEle = $(this).prev(".sub_container").clone(true);
cloneEle.attr("class","sub_container"+count)
cloneEle.find("input[type='text']").val('');
cloneEle.find('input[type="submit"]').val("Submit");
cloneEle.find('input[type="submit"]').attr("id","btnSubmit"+count)
cloneEle.appendTo('.container');
$('.preview_message').last().html('');
$('.preview_name').last().html('');
});
jsfiddle demo

Show Input Box on Check

You can see in the paper form attached what I need to convert into a web form. I want it to show the check boxes and disable the input fields unless the user checks the box next to it. I've seen ways of doing this with one or two elements, but I want to do it with about 20-30 check/input pairs, and don't want to repeat the same code that many times. I'm just not experienced enough to figure this out on my own. Anyone know anywhere that explains how to do this? Thanks!
P.S. Eventually this data is all going to be sent through an email with PHP.
I don't think this is a good idea at all.
Think of the users. First they have to click to enter a value. So they always need to change their hand from mouse to keyboard. This is not very usable.
Why not just give the text-fields? When sending with email you could just leave out the empty values.
in your HTML :
//this will be the structure of each checkbox and input element.
<input type="checkbox" value="Public Relations" name="skills" /><input type="text" class="hidden"/> Public Relations <br/>
in your CSS:
.hidden{
display:none;
}
.shown{
display:block;
}
in your jQuery:
$('input[type=checkbox]').on('click', function () {
// our variable is defined as, "this.checked" - our value to test, first param "shown" returns if true, second param "hidden" returns if false
var inputDisplay = this.checked ? 'shown' : 'hidden';
//from here, we just need to find our next input in the DOM.
// it will always be the next element based on our HTML structure
//change the 'display' by using our inputDisplay variable as defined above
$(this).next('input').attr('class', inputDisplay );
});
Have fun.
Since your stated goal is to reduce typing repetitive code, the real answer to this thread is to get an IDE and the zen-coding plug in:
http://coding.smashingmagazine.com/2009/11/21/zen-coding-a-new-way-to-write-html-code/
http://vimeo.com/7405114

Clear default values using onsubmit

I need to clear the default values from input fields using js, but all of my attempts so far have failed to target and clear the fields. I was hoping to use onSubmit to excute a function to clear all default values (if the user has not changed them) before the form is submitted.
<form method='get' class='custom_search widget custom_search_custom_fields__search' onSubmit='clearDefaults' action='http://www.example.com' >
<input name='cs-Price-2' id='cs-Price-2' class='short_form' value='Min. Price' />
<input name='cs-Price-3' id='cs-Price-3' class='short_form' value='Max Price' />
<input type='submit' name='search' class='formbutton' value=''/>
</form>
How would you accomplish this?
Read the ids+values of all your fields when the page first loads (using something like jquery to get all "textarea", "input" and "select" tags for example)
On submit, compare the now contained values to what you stored on loading the page
Replace the ones that have not changed with empty values
If it's still unclear, describe where you're getting stuck and I'll describe more in depth.
Edit: Adding some code, using jQuery. It's only for the textarea-tag and it doesn't respond to the actual events, but hopefully it explains the idea further:
// Keep default values here
var defaults = {};
// Run something like this on load
$('textarea').each(function(i, e) {
defaults[$(e).attr('id')] = $(e).text();
});
// Run something like this before submit
$('textarea').each(function(i, e){
if (defaults[$(e).attr('id')] === $(e).text())
$(e).text('');
})
Edit: Adding some more code for more detailed help. This should be somewhat complete code (with a quality disclaimer since I'm by no means a jQuery expert) and just requires to be included on your page. Nothing else has to be done, except giving all your input tags unique ids and type="text" (but they should have that anyway):
$(document).ready(function(){
// Default values will live here
var defaults = {};
// This reads and stores all text input defaults for later use
$('input[type=text]').each(function(){
defaults[$(this).attr('id')] = $(this).text();
});
// For each of your submit buttons,
// add an event handler for the submit event
// that finds all text inputs and clears the ones not changed
$('input[type=submit]').each(function(){
$(this).submit(function(){
$('input[type=text]').each(function(){
if (defaults[$(this).attr('id')] === $(this).text())
$(this).text('');
});
});
});
});
If this still doesn't make any sense, you should read some tutorials about jQuery and/or javascript.
Note: This is currently only supported in Google Chrome and Safari. I do not expect this to be a satisfactory answer to your problem, but I think it should be noted how this problem can be tackled in HTML 5.
HTML 5 introduced the placeholder attribute, which does not get submitted unless it was replaced:
<form>
<input name="q" placeholder="Search Bookmarks and History">
<input type="submit" value="Search">
</form>
Further reading:
DiveintoHTML5.ep.io: Live Example... And checking if the placeholder tag is supported
DiveintoHTML5.ep.io: Placeholder text
1) Instead of checking for changes on the client side you can check for the changes on the client side.
In the Page_Init function you will have values stored in the viewstate & the values in the text fields or whichever controls you are using.
You can compare the values and if they are not equal then set the Text to blank.
2) May I ask, what functionality are you trying to achieve ?
U can achieve it by using this in your submit function
function clearDefaults()
{
if(document.getElementById('cs-Price-2').value=="Min. Price")
{
document.getElementById('cs-Price-2').value='';
}
}

Categories