adding input field dynamically causes problems - javascript

I'm working on a html page and I have a problem when adding a new input field to the form. The problem is that, the content of the other input fields is resetted when the new field is added.
The code for adding a new input text is the following:
var TSLOT =
[ "<div id=\"TSLOT_n_\">",
"From: <input type=\"text\" id=\"from_n_\" autocomplete=\"off\">",
"By letter: <input type=\"text\" id=\"letter_n_\" autocomplete=\"off\">",
"To: <input type=\"text\" id=\"to0-_n_\" autocomplete=\"off\">",
"<input type=\"text\" id=\"to1-_n_\" autocomplete=\"off\">",
"<BR></div>" ].join("");
function addSlotTransition() {
document.getElementById( "Delta" ).innerHTML += TSLOT.replace( /_n_/g, Delta_size++ ); }
Am I missing something?

When you use .innerHTML, it creates a new DOM tree from the parsed innerHTML and rewrites it, so everything not present in the HTML is lost. Use a real append:
document.getElementById( "Delta" ).insertAdjacentHTML( 'beforeend', TSLOT.replace( /_n_/g, Delta_size++ ) );
JS Fiddle Demo

Related

Adding new input fields on check box ticked

I have a table with 3 text fields
i want to add the same text fields on clicking check box i have the following code
how can i do it with php and javascript
echo "<td>Screen ".$i."</td>";
echo "<td><input type='text' id='filmname".$k."' name='filmname".$k."'value='".$prefilm."'></td>";
echo "<td><input type='text' id='Language".$k."' name='Language".$k."'value='".$prelang."'></td>";
echo "<td><input type='text' id='showtime".$k."' name='showtime".$k."'value='".$prescreen."'></td>";
echo "<td ><input type='checkbox' class='Checkbox' id='addshow".$k."' autocomplete='off'
name='addshow".$k."' value='addshow' onclick='addshow(".$k.")</td>";
It would be great if you can clarify where you want to add which text fields when the checkbox got checked.
Two ideas:
You can create your text fields at the same time when you create your table and then hide/show them with CSS and JavaScript. (Preferred)
Add a click listener to your checkbox and create your text fields dynamically with JS with document.createElement('input') Learn more here
Code examaple for the 2nd option:
const check = document.querySelector('input[type=checkbox]');
check.addEventListener('click', createTextInput);
function createTextInput() {
const target = document.querySelector(YOUR TARGET SELECTOR);
const input = document.createElement('input');
input.setAttribute('type', 'text');
input.addEventListener(OPTIONAL IF YOU WANT)
target.appendChild(input); // this adds the new input into your target
}

faceMocion input tag not get bind in jQuery

when i use <input type="hidden" value="asombro" class="facemocion" /> in body then its work correctly ,
but when i try to bind same tag with jQuery like
html= html + "<input type="hidden" value="asombro" class="facemocion" />"
it not get work
You will need to use single quotes for the string:
html += '<input type="hidden" value="asombro" class="facemocion" />';
Or escape the double quotes inside it:
html += "<input type=\"hidden\" value=\"asombro\" class=\"facemocion\" />";
You can do it like more jquery way rather than creating it as string,
var hidden = $("<input>", {
type: 'hidden',
value: 'asombro',
'class': 'facemoion'
});
$("body").append(hidden);
Try make this way.
html += '<input type="hidden" value="asombro" class="facemocion"/>
$('body').append(html);
now use the plugin.
$('.facemocion').faceMocion();

2-step dynamical echo of a php in innerHTML

step 1: I have a form where input fields will be generated dynamically by innerHTML.
var d = document.getElementById("d1p_1");
d.innerHTML += "<input class='add' name='field_" + i + "' type='text'>";
step 2: now I would like to echo a php variable of each value to each dynamically generated input field. Something like:
d.innerHTML += "<input class='add' name='field_" + i + "' type='text' value='"<?php echo $field_" + i + "; ?>" + "'>
How can I archieve that?
Thanks in advance.
To give further information:
This is for a form where an user can add fields, depending from how many fields he needs and will be adding. Now it could be that an user adds more fields than he usually needs and enters data somewhere between field_1 and field_280. To catch the field_x where he entered data I need to echo the value of that input field.
$field_1 = value of field_1 if given;
...
$field_280 = value of field_280 if given;
The innerHTML will add the input fields dynamically by a counter for i. So I dont know what input will be given on which field. Thats why I need to generate the PHP echo part dynamical as well. Like:
<?php echo $field_" + i + "; ?>
The whole process:
form -> contains first just one input field (user will make some inputs) -> by clicking a button there will be added further input fields (1 click 1 field and user does not need to fill in data before he can add another fields) -> now imagine that a user will add 3 fields and has given input on first and third input field -> name="field_1" and name="field_3" ->
the name of each input field is generated by i++ -> the value is empty otherwise the form will be posted -> now the user will submit the form.
this means the value to echo would be $field_3 = (isset($_POST['field_3'])) ? $_POST['field_3']; : ''; -> this variable exist for all i so each variable is set in the php part before BUT to catch the right input name="field_i" with $field_i and to echo this match is the problem.
So by clicking submit the page would be reloaded and instead of only just one input field like from before now would be there 2 input fields. first would be name="field_1" and the second would be name="field_3" because user has left out input name="field_2" before. So name="field_3" needs to echo the right value depending from a dynamically generated name="field_"+ i +"what means that when the name tag is generated dynamically the php tag needs also to be generated dynamically to match each other.
i is a JavaScript variable so including it in a php declaration is giving you problems
You may implement your string concatenation out of the php code as follows
<?php
$field_="stavo";
?>
<script type="text/javascript">
var i=10;
var d = document.getElementById("d1p_1");
d.innerHTML+= "<input class='add' name='field_" + i + "' type='text'>";
d.innerHTML += "<input class='add' name='field_" + i + "' type='text' value='<?php echo $field_; ?>"+i+"'>";
</script>
Of course you must be having this in your Html
<div id="d1p_1"></div>

String with whitespace in javascript

I have a String "Magic Word". I need to use it as value in html checkbox generated by javascript.
in javascript
var itemValue= "Magic task";
var opt = "<input type='checkbox' name='test' id='test' value="+ itemValue+ "/>"+itemValue+ "<br />";
alert(opt);
$(optionDiv).append(opt);
In alert it is displaying the actual value but after submitting form i am getting only first word as value.It is ignoring second word.
Thanks
Ravi Kant
You need to wrap the value with single quotes:
"<input type='checkbox' name='test' id='test' value='" + itemValue + "' />"
If you are using jQuery (as I see the usage of $ in your code), it's better to do it with jQuery itself:
var itemValue= "Magic Word";
var opt = $('<input>').attr({
type: 'checkbox',
name: 'test',
id: 'test',
value: itemValue
});
It will prevent any furthur error, for example if you have some ' in your string:
var itemValue= "Magician's Word";
When you do not use quotes the attributes value ends at the whitespace. Your rendered string appears as
<input type='checkbox' name='test' id='test' value=Magic Word />
So the parser sees
value=Magic
and an attribute Word with no value. You can see that with the coloring in the post above.
You need to add single quotes around the value
var opt = "<input type='checkbox' name='test' id='test' value='" + itemValue + "' />"+ itemValue+ "<br />";
^ ^
Where does this fail? If you have a ' in your string. You would need to add a replace method and swap it for #apos;
itemValue = itemValue.replace(/'/g,"#apos;");

Javascript controls html so the external js does not see the html name field

I am building a form using a js+html and I ran into a problem. There's a part of my form where user should be able to click on a textfield and pick a date & time from a calendar(anytime.js by MAM3), and since my form(partial code) is built this way:
third_list = "<table class='table'>";
if (radio_array[genIndex] == reserve) {
third_list += "<tr><td id='Date:'><label><span id='Date'>Date:</span><input type='text' id='Date' name='_date' size='20' onfocus='showMessage()'/></label></td>";
third_list += "<td id='Time:'><label><span id='Time'>Time:</span><input type='text' id='Time' name='_time' size='20' /></label></td>";
document.getElementById("third").innerHTML = third_list;
l3_value = "";
return;
}
and by putting this to the html:
<script type="text/javascript">
AnyTime.widget
( "Date",
{ format: "%m/%d/%Z" }
);
AnyTime.widget
( "Time",
{ format: "%h:%i:%p" }
);
</script>
it does not pop-up a calendar.
Side notes: I have included all of the required js&css files and tried to see if it works on a seperate text field out from js, and it works. I think the reason it doesnt work is it is controlled by js, so the anytime.js does not see it as a html name field.
SN2: onfocus='showMessage()' in my js is to show a message when a user clicks on a text field.
How do I make it work?
A couple of issues:
First, you have more than one element with the id values Date and Time. id values must be unique in the document. I expect the script isn't getting the element it expects and is failing to init. The documentation for AnyTime seems to suggest it uses the first argument you give AnyTime.widget as an id and expects to get an input field. In your case, it usually won't on most browsers, because when faced with an invalid structure featuring duplicate ids, most browsers will return the first one when you ask for "the" element with that id, which in your case is a span rather than an input field.
Your Date elements:
<span id='Date'>Date:</span><input type='text' id='Date' ... />
<!-- ^--- one ^--- two -->
The Time is the same sort of problem.
Separately from that, I suspect you need to ensure that the elements exist when you call AnyTime.widget. I don't know where you have that script tag that calls it, but what you need to do is make this calls after you've executed the line
document.getElementById("third").innerHTML = third_list;
...so that the elements in question exist in the DOM. So for instance:
third_list = "<table class='table'>";
if (radio_array[genIndex] == reserve) {
third_list += "<tr><td id='Date:'><label><span id='Date'>Date:</span><input type='text' id='Date' name='_date' size='20' onfocus='showMessage()'/></label></td>";
third_list += "<td id='Time:'><label><span id='Time'>Time:</span><input type='text' id='Time' name='_time' size='20' /></label></td>";
document.getElementById("third").innerHTML = third_list;
l3_value = "";
setUpWidgets();
return;
}
// ...elsewhere in the same scope or a containing scope:
function setUpWidgets() {
AnyTime.widget
( "Date",
{ format: "%m/%d/%Z" }
);
AnyTime.widget
( "Time",
{ format: "%h:%i:%p" }
);
}
That creates a function, which you call when the elements are there.
Side note: You also have an id that looks like this:
<td id='Date:'>
Although that's a valid id in HTML5, it wasn't valid in HTML4 and isn't valid in CSS. So if you try to use that id in a CSS-style selector (for instance, with jQuery), you'll probably run into trouble.

Categories