Attempting to preview form input jQuery - javascript

I am attempting to preview my name and step element in my form, so the user can see if they have made a mistake. I am able to preview the step however the name just won't work. Can anyone see why?
http://jsfiddle.net/pocockn/rw54b/
$(document).ready(function() {
var commentNode = $('#lp-step'),
nameNode = $('#lp-name'),
name = $('#name');
$('#live-preview-form input, #live-preview-form textarea').bind('blur keyup',function() {
commentNode.text($('#step_1').val());
commentNode.html($('#lp-step').html().replace(/\n/g,'<br />'));
if($('#name').val()) {
nameNode.text(name.val() + ' says:');
}
else {
return false;
}
});
});

You can't have two elements with the same ID, if you do it will only select the first element it finds. (in this case its the div which is always empty and never runs your if statement). You have your div with id=name and your input. So I changed your div id to nameDiv instead.
Id's should be unique to avoid confusion.
<div id="nameDiv">
<label for="name">Enter recipe name:</label>
<input type="text" id="name" name="name">
<br />
</div>
http://jsfiddle.net/trevordowdle/rw54b/1/

Related

Use image as a hyperlink and to save a textbox input value?

In my website, I have a textbox which I'm using to ask the user for their name. Below I have 2 images, a cancel "button" which is just an image which has an tag to take it back to the index, and a Go image which is linked to another HTML page where the input taken from the text box will be used to fill in a paragraph. This page is linked below:
I am fine with how the cancel image is functioning but is it possible for me to use the Go image to take me to my other HTML page as well as to store the data input into the "your name" text box?
<div class="name_input_box">
<input type="text" placeholder="Your name" id="name" required />
<label for="name" class="label_name">
</label>
</div>
my code for the input box^
<a href="Add_page.html">
<img src="assets/Go_button.png" img style="height:35%; width:35%;">
</a>
My code for the "go" image^
I appreciate this might seem simple but I can't find any video tutorials on how to tackle this, many thanks to anyone who takes the time to help me on Easter Sunday :)
Either use localStorage or just have a form
<form action="Add_page.html">
<div class="name_input_box">
<label for="name" class="label_name"><input type="text" placeholder="Your name" name="name" required /></label>
<input type="image" src="assets/Go_button.png" img style="height:35%; width:35%;">
</div>
</form>
and use the location.search to get the name.
If I understand your questions well, I think this is what you are looking for.
Local storage stores your data for your and you can get your data any time you need it.
try this out linking this script to your html code and making reference to the right id's.
// get data from the input tag/local storage value
var input_data = document.getElementById('input_data').value
//local storage key
var key_name = 'UserName';
// paragraph to fill input ..you can p tag for this
var result_screen = document.getElementById('result_screen')
// image link / button
var goBtn = document.getElementById('goBtn');
goBtn.onclick = function () {
// To check for empty input value
if (key_name && value) {
localStorage.setItem(key_name, input_data);
location.reload();
}
}
// loop through the input value entered by users
for (var i = 0; i < localStorage.length; i++) {
var key_name = localStorage.key_name(i);
var input_data = localStorage.getItem(key_name);
result_screen.innerHTML += `${key_name}: ${value}<br>`;
}

How to POST additional values from inputs outside the form [duplicate]

I've read many blogs and posts on dynamically adding fieldsets, but they all give a very complicated answer. What I require is not that complicated.
My HTML Code:
<input type="text" name="member" value="">Number of members: (max. 10)<br />
Fill Details
So, a user will enter an integer value (I'm checking the validation using javascript) in the input field. And on clicking the Fill Details link, corresponding number of input fields will appear for him to enter. I want to achieve this using javascript.
I'm not a pro in javascript. I was thinking how can I retrieve the integer filled in by the user in input field through the link and displaying corresponding number of input fields.
You could use an onclick event handler in order to get the input value for the text field. Make sure you give the field an unique id attribute so you can refer to it safely through document.getElementById():
If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">. Create new elements by means of document.createElement(), and use appendChild() to append each of them to the container. You might be interested in outputting a meaningful name attribute (e.g. name="member"+i for each of the dynamically generated <input>s if they are to be submitted in a form.
Notice you could also create <br/> elements with document.createElement('br'). If you want to just output some text, you can use document.createTextNode() instead.
Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes() and removeChild() together.
<html>
<head>
<script type='text/javascript'>
function addFields(){
// Generate a dynamic number of inputs
var number = document.getElementById("member").value;
// Get the element where the inputs will be added to
var container = document.getElementById("container");
// Remove every children it had before
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
// Append a node with a random text
container.appendChild(document.createTextNode("Member " + (i+1)));
// Create an <input> element, set its type and name attributes
var input = document.createElement("input");
input.type = "text";
input.name = "member" + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
}
}
</script>
</head>
<body>
<input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
Fill Details
<div id="container"/>
</body>
</html>
See a working sample in this JSFiddle.
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields) {
x++;
$(wrapper).append('<div><input type="text" name="mytext[]"/>Delete</div>'); //add input box
} else {
alert('You Reached the limits')
}
});
$(wrapper).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container1">
<button class="add_form_field">Add New Field
<span style="font-size:16px; font-weight:bold;">+ </span>
</button>
<div><input type="text" name="mytext[]"></div>
</div>

multiple div with same template

I have a 'users page'. I would like to give a textbox for entering the no. of users. On click of submit 'n' no of user forms need to be presented to user.
User1
first name -
last name -
User2
first name -
last name -
.
.
.
UserN
first name -
last name -
I don't know the value of 'N' upfront. So it won't be a good idea to write multiple 'divs' in my html.
Requirement:Rather I want to have a user template div. And copy the template 'n' times depending on the value of 'n' in the textbox. But I would also want all the 'divs' to have different ids like 'user1', 'user2' etc.
I cannot figure out a way to do this apart from populating my html with too many 'divs'. Would need help achiving the Requirement specified.
Looking for a template like:-
<div id="user-template" class="hidden">
<label class="lbl"><b>Handle:</b></label><input type="text" id="first_name" value=""/>
</div>
And wanted to have id="user-template" change for all new divs.
You can try something like this:
You can make a template and append it to the DOM for the number entered in the input field.
$(document).ready(function() {
$("#createForms").click(function() {
var numOfForms = $("#numOfForms").val();
var template = $('#hidden-template').html();
for (var i = 0; i < numOfForms; i++) {
$('#targetDiv').append("<p>User" + (i + 1) + ":</p>");
$('#targetDiv').append(template);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="numOfForms"></input>
<input type="button" id="createForms" value="Get Fields"></input>
<div id="targetDiv"></div>
<script id="hidden-template" type="text/x-custom-template">
<div id="user-template" class="hidden">
<p>First Name:
<input type="text" name="firstName"></input>
</p>
<p>Last Name:
<input type="text" name="lastName"></input>
</p>
<br>
</div>
</script>
A simple way is to write a function that takes the n value and returns the actual dom that you can append to some parent element on your page. A simple example below:
function createNDivs(n) {
if(!n) return;
var fragment =document.createDocumentFragment();
for(var i=0;i<n;i++) {
var div = document.createElement('div');
fragment.appendChild(div);
}
return fragment;
}

Set the default value of an input text

my requirement is to save the entire "html" inside a div, but when i load an "html" with text fields to a div and then editing the value of the text box, the newly set value doesn't reflect in the core "html". I tried to inspect the value with fire bug and it remains the same or no value at all.With "jquery" i tried to set attribute but no attribute name value is created. how can i set the value of text fields and then get that "html" with the newly set value.
here is my html
<div class="sub_input_box">
<input type="text" / class="boreder_line">
<input type="text" id="txt" value=""/>
<input type="hidden" id="hid" />
<div class="clear"></div>
</div>
and the jquery i used to set attribute
$("#txt").attr("value", "some value");
Chances are you're calling your jQuery code before the HTML input part. You can either place the jQuery stuff below it, or if you don't want to, you can do something like this:
$(document).ready(function(){
$("#txt").attr("value", "some value");
});
That will only run when the page is fully loaded.
However, it's unclear if you're using AJAX to load those inputs into your DOM. If so, you need to call $("#txt").attr("value", "some value"); in the onSuccess callback function which is fired after the AJAX successfully responds.
You can try something like this:-
<input name="example" type="text" id="example"
size="50" value="MyDefaultText" onfocus="if(this.value=='MyDefaultText')this.value=''"
onblur="if(this.value=='')this.value='MyDefaultText'" />
Have you tried:
$("#txt").val("Hello World!");
For setting the text value, and,
var my_string = $("#txt").val();
For getting the text value.
Let me know if it works.
Excellent question. You would think clone would do this on its own, alas, it doesn't.
Here is a sample than you can hopefully adapt to do what you need
HTML
<div id=divToCopy>
<input name=i1 value=foo><br>
<input name=i2 value=bar>
</div>
<input type=button onclick=copyDiv(); value='Copy the div'>
<div id=newDiv>
the copy will go here
</div>
JavaScript
function copyDiv() {
$('#newDiv').html($('#divToCopy').clone());
$('#divToCopy :input').each(function() {
var child=0;
for (var i = 0; i < this.attributes.length; i++) {
var attrib = this.attributes[i];
var prop=$(this).prop(attrib.name);
$($('#newDiv').find(' :input')[child]).prop(attrib.name,prop);
child++;
}
});
}
But it does work: http://jsbin.com/eXEROtU/1/edit
var html = '<input type="text" id="txt" value=""/>';
$(document).ready(function() {
$("#load").click(function() {
$("#sub_input_box").html(html);
});
$("#inspect").click(function() {
alert($("#txt").val());
});
});
$(document).on('focusout','input[type="text"]',function(a){
console.log(a.target.value);
a.target.setAttribute("value",a.target.value);
});
this is the solution i found, i had to set the value attribute explicitly on loose focus from the text field

get sibling that has id

So I have the following structure:
<div id="some id">
<div>
<input id="some other id" ....>
.....bunch of other inputs with no id field....
<select onclick="findSiblingWithId()">
</div>
<div>
<input id="some other id" ....>
.....bunch of other inputs with no id field....
<select onclick="findSiblingWithId()">
</div>
<div>
<input id="some other id" ....>
.....bunch of other inputs with no id field....
<select onclick="findSiblingWithId()">
</div>
So in my findSiblingWithId i don't know the id I'm looking for, all I know is that for the other components in the same div, only one will have an id. How can I get that ?
Edit:
Since it seems I didnt explain well enough I'll try to add more info. So I want for example when the select component changes (here it could be a button or anything, it doesnt matter) to get the corresponding <input id="some other id" ..> from the same div.
Like I tried to explain above, I have one huge div, the <div id="some id">, now this contains a number of smaller <div> without ids.
Each of these smaller divs will have ONE inputfield with an ID and a bunch of other without an ID. Now on an action, doesn't matter if a button click or whatever, from a component located IN THE SAME div (I thought the correct work would be 'sibling') is there a way I can find the input that has an ID attribute?
Regards,
Bogdan
You could iterate over all children of the parent:
function findSiblingWithId(element) {
var siblings = element.parentNode.children,
sibWithId = null;
for(var i = siblings.length; i--;) {
if(siblings[i].id) {
sibWithId = siblings[i];
break;
}
}
if(sibWithId) [
// found it
}
};
You have to pass the clicked element (I hope you have a proper select field);
<select onclick="findSiblingWithId(this)">
Consider to attach the event handler for the change event, if you want to have it triggered when the user selected a value.
Recursively iterate through the parent div and add logic to separate the inputs that have IDs
function findSiblingWithId(element) {
var sibling = null;
if (element.parentNode != null) {
sibling = element.parentNode.nextSibling;
// Then go through the child elements of your sibling node and get the one with an id
}
}
Using jQuery:
<!--Modify HTML so input is -->
<select onclick="findSiblingWithId(this)">
findSiblingWithId(elem){
return $(elem).siblings("[id]"); //if you need all
//return $(elem).siblings("[id]:eq(0)"); //if you need only first
}
The most direct way to get the value that has this id among the siblings is to use the sibling's filter like this:
let my_id = ...
$(this).siblings(`div[id=${my_id}]`)

Categories

Resources