Dynamically add text box in javascript - javascript

I dynamically add a text box whenever a user clicks a button to add more, which works fine. However, in PHP when I get the submitted field values by $_POST['skills'] , I only receive the first text box value, not the dynamically added ones. I'm almost positive there is something wrong with the way I am adding the text boxes in javascript.
I use the following method to add a text box field:
function addTextBoxField()
{
var input = document.createElement('input');
input.type = "text";
input.name = "skills[]";
input.size = "30";
var container = document.getElementById("skillfield");
container.appendChild(input);
}
The HTML code I have for the text box is :
...
<td>
<div id="skillfield">
<input type="text" size="30" name="skills[]" />
</div>
</td>
<td><div class="button">+ Add</div></td>
Here is the php code as well:
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$allskills = $_POST['skills'];
$size = count($_POST['skills']);
print_r($allskills);
}
The output is the following, even though I inputted three values
Array ( [0] => java )

Your field name is skills not skill .So it should be $_POST['skills'].$_POST['skills'] is an array in this case. So access try with var_dump($_POST['skills']); and you will see all the values.

As far as the $_POST['skills'] is an array, Try this..
$skill = $_POST['skills'];
foreach($skill as $value){
echo $value;
}

do you mean the values of $_POST['skills']
i dont think there is something wrong with your javascript, what is wrong is how you read the post data in your php. The post data will be an array in this case, so you access it like this $_POST['skills'][0] //value of 1st input $_POST['skills'][1] //value of 2nd input

$_POST['skills'] is an array,So use print_r() to view the array.You may use as follows
<script type="text/javascript">
function addTextBoxField()
{
var input = document.createElement('input');
input.type = "text";
input.name = "skills[]";
input.size = "30";
var container = document.getElementById("skillfield");
container.appendChild(input);
}
</script>
<form method ="post">
<td>
<div id="skillfield">
<input type="text" size="30" name="skills[]" />
</div>
</td>
<td>
<input type="submit" name="submit" value="Submit"/>
</td>
</form>
<td><div class="button">+ Add</div></td>
<?php
if(isset($_POST['submit']) && $_POST['submit'] == 'Submit'){
echo "<pre>";
print_r($_POST['skills']);
echo "</pre>";
}
?>

you could use the array length. Try to this
for($i=0;$i<=count($skills)-1;$i++)
{
$per=$skills[$i]*$skills[$i];
echo $per;
}

Related

get radio button value (PhP MySQL and ajax)

Newbie here..
I have this code for my displaying the database records in a table,
I want to know how do i get the value of radio button (the radio button contains the id of selected row). I tried doing it in javascript but no luck.
table.php
<table border="1">
<th></th>
<th>Particulars</th>
<th>Amount</th>
<?php
include('includes/config.php');
$qry = $con->prepare('SELECT * FROM fees');
$qry->execute();
$row = $qry->rowCount();
while ($row = $qry->fetch(PDO::FETCH_ASSOC)) {
$id = $row['fee_id'];
$fee = $row['fee_name'];
$amt = $row['amount'];
?>
<?php echo "
<tr title='Click to edit or delete record'>
<td><input type = 'radio' name = 'radio' class ='radio' value = $row[fee_id]></td>
<td>$fee</td>
<td>$amt</td>
</tr>
"; ?>
<?php } ?>
</table>
<input type="button" value="Delete Selected Fee" style="width:250px; height:40px;font-weight:bold;" onclick="delete();"><br><br>
javascript code
<script type="text/javascript">
function delete(){
if (document.getElementsByClassName(this.class).checked){
var val = document.getElementsByClassName(this.class).value;
alert (val);
}
}
</script>
Use this
function delete(){
if($('input[name="radio"]').is(':checked')){
var val = $('input[name="radio"]').val();
console.log(val);
}
}
I suggest you to use hidden field instead if you don't want to show. The property of radio buttons is to show only true / false value. It may be on / off or yes / no, according to your uses. Use like
<input type = 'hidden' name = 'whatever' class ='radio' value =<?php echo $row['fee_id']; ?>>
You can try this, this should get your radio button value using your input name.
<script type="text/javascript">
function delete(){
if($('input[name="radio"]').is(':checked')){
var val = $('input[name="radio"]').val();
alert (val);
}
}
</script>
Following code will give you your radio button value
<script type="text/javascript">
function delete(){
if($('input[name="radio"]').is(':checked')){
var val = $('input[name="radio"]').val();
alert (val);
}
}
</script>
you can use console.log(val);

Javascript function not returning a value

I have a javascript function that check for a value from a text box and the if the text box is not blank it outputs a statement. The text box take a numeric value, i want to include that numeric value that is output to html.
here is the html
<br><label id="cancelphoneLabel">1-800-555-1111</label>
<br><label id="mdamountLabel">Monthly Donation:
<td>
<input type="text" id="mdamountBox" style="width:50px;" name="md_amt" value="" placeholder="Monthly" onkeyup="monthlycheck()" autocomplete="off">
<br><label id="mnthlychkdiscoLabel"> </label>
and the Javascript
function monthlycheck() {
var mnthchk = document.getElementById("mdamountBox").innerHTML; <---i want to pass the value of this box
var cancelPhone = document.getElementById("cancelphoneLabel").innerHTML;
if (mnthchk.value != "") {
var newHTML = "<span style='color:#24D330'> Your Monthly pledge in the amount of $<label id='dollarLabel'> </label> is valid and will be deducted this time every month<br> untill you notify us of its cancellation by calling <label id='cancelphonelistLabel'> </label> </span>";
document.getElementById("mnthlychkdiscoLabel").innerHTML = newHTML;
document.getElementById("cancelphonelistLabel").innerHTML = cancelPhone;
document.getElementById("dollarLabel").innerHTML = mnthchk; <----passed to here
i cant get the value passed, it only shows blank, i can hardcode a value and will output fine, which is how the jsfiddle is currently http://jsfiddle.net/rn5HH/4/
thanks in advance
Input elements don't have child nodes, therefore innerHTML is blank. If you want to read their value, use the value property.
Your line:
var mnthchk = document.getElementById("mdamountBox").innerHTML;
Should be:
var mnthchk = document.getElementById("mdamountBox");
Then you can get the value of the text input like this:
var newmnthchk = mnthchk.value;
Working JS Fiddle here: http://jsfiddle.net/rn5HH/10/
use document.getElementById("mdamountBox").value
The problem here is you are trying to get the innerHtml, where you want the value. From your fiddle, just change this line:
var mnthchk = document.getElementById("mdamountBox").innerHTML;
...to this:
var mnthchk = document.getElementById("mdamountBox").value;
check below code :
HTML Code
<br><label id="cancelphoneLabel">1-800-555-1111</label>
<br><label id="mdamountLabel">Monthly Donation:
<td>
<input type="text" id="mdamountBox" style="width:50px;" name="md_amt" value="" placeholder="Monthly" onkeyup="monthlycheck()" autocomplete="off">
<br><label id="mnthlychkdiscoLabel"> </label>
Javascript Code
function monthlycheck() {
var mnthchk = document.getElementById("mdamountBox").value;
var cancelPhone = document.getElementById("cancelphoneLabel").innerHTML;
if (mnthchk.value != "") {
var newmnthchk = '5';
newmnthchk = mnthchk;
var newHTML = "<span style='color:#24D330'> Your Monthly pledge in the amount of $<label id='dollarLabel'> </label> is valid and will be deducted this time every month<br> untill you notify us of its cancellation by calling <label id='cancelphonelistLabel'> </label> </span>";
document.getElementById("mnthlychkdiscoLabel").innerHTML = newHTML;
document.getElementById("cancelphonelistLabel").innerHTML = cancelPhone;
document.getElementById("dollarLabel").innerHTML = newmnthchk;
}
}
This is working code perfectly checked on Fiddle
,you need to get DOM value using
var mnthchk = document.getElementById("mdamountBox").value;

Multiple dynamic input text javascript

Im having trouble creating multiple input texts with javascript.
My point is create a new input text everytime the input before is completed. (parent?)
Ive some code for comboboxs, but this time I need just input text box.
How can I do that ?
I've found this code:
<script type="text/javascript">
function addInput()
{
var x = document.getElementById("inputs");
x.innerHTML += "<input type=\"text\" />";
}
</script>
<input type="button" onmousedown="addInput();" />
<div id="inputs"></div>
But for my problem button is obsolete.
I think my event trigger will be something arround this "when user click in an input text box and it is != blank it creates a new one".
I migth need some ID to identify every input text box.
Cheers.
JSBIn Demo
Guess this helps:
<div id="myDiv">
<input type="text" id="txt_1" onkeydown="newTextBox(this)" />
</div>
<script type="text/javascript">
function newTextBox(element){
if(!element.value){
element.parentNode.removeChild( element.nextElementSibling);
return;
}
else if(element.nextElementSibling)
return;
var newTxt = element.cloneNode();
newTxt.id = 'txt_'+( parseInt( element.id.substring(element.id.indexOf('_')+1)) + 1);
newTxt.value='';
element.parentNode.appendChild(newTxt);
}
</script>
HTML code:
<div id="inputcontainer">
<input type="text" name="input0" id="input0" onkeyup="addInput();" />
</div>
And Javascript:
var currentindex = 0;
function addInput(){
var lastinput = document.getElementById('input'+currentindex);
if(lastinput.value != ''){
var container = document.getElementById('inputcontainer');
var newinput = document.createElement('input');
currentindex++;
newinput.type = "text";
newinput.name = 'input'+currentindex;
newinput.id = 'input'+currentindex;
newinput.onkeyup = addInput;
container.appendChild(newinput);
}
}
This will add a new input to the list only when the last input is not empty.
http://jsfiddle.net/HJbgS/
Have a look at the onchange event on your text input field. You can use it, like you use onmousedown on your button.
See http://www.w3schools.com/jsref/event_onchange.asp for an example.
In your addInput() function you should then check if the input of the previous textfield is != "".

Text area content changes to "value" after displaying the content for a second

I have a query regarding the textarea field , I came across a very weird problem and I am trying to figure it out.
Firstly , here is what I am trying to do :
I have a drop down menu from which I select one of the template .
when selected I display the value of the template in the textarea { this is the problematic part }
after that I process the data from the text area ..and well rest is not in picture.
Problem Description :
when i try to display the value selected from the Drop down menu to the text area using the function : document.getElementById("mytext").innerHTML=myvalue.value;
it displays for a second and then the page reloads and shows the default value again .
here is my code:
javascript :
<SCRIPT language="javascript">
function add(index_array) {
//create the form
var myform = document.createElement("form");
myform.id="k_form"
for ( i =0 ; i <index_array.length ; i ++)
{
var mytext = document.createElement("input");
mytext.tpye="text";
mytext.name=index_array[i];
mytext.value=index_array[i];
mytext.id=index_array[i];
myform.appendChild(mytext);
}
mydiv=document.getElementById("d_div");
mydiv.appendChild(myform);
}
</SCRIPT>
<SCRIPT>
function getkeywords() {
// var current_Date = new date();
// document.write(current_Date);
var index_array = new Array();
var myString = "one and a two and a three = $ and four = $ and five = $";
var splitresult = myString.split(" ");
for(i = 0; i < splitresult.length; i++)
{
if (splitresult[i] == "$" && i > 1 ) //retireving the keywords..
{
index_array.push(splitresult[i-2]);
}
}
add(index_array);
/*
console.log("inside the if statement");
index_array.push(splitresult[i-2]); //saving the keywords for creating a new form with these as inputs....
}}
for ( i = 0 ; i < index_array.length ; i++ )
{
add(index_array[i]);
}
*/
}
</SCRIPT>
<script>
function populate_text()
{
var myvalue = document.getElementById("rawquery");
document.getElementById("mytext").innerHTML=myvalue.value;
}
</script>
the function "populate_text is the one that populates the textarea .
My HTML code is below :
</HEAD>
<BODY>
<FORM>
<BR/>
<div align = "center">
<form method = "post" action = "<?php echo $_SERVER['PHP_SELF']; ?>">
Select a Template<br />
<select name = "element" id = "rawquery">
<option>Select</option>
<option value = "Alpha query">Alpha</option>
<option value = "Betaquery">Beta</option>
<option value = "Gamma query">Gamma</option>
<option value = "Epsilon query">Epsilon</option>
</select>
<br />
<input type = "submit" onclick="populate_text()" name = "submit"><br /><br />
</form>
<textarea id = "mytext" name = "raw" rows = "10" cols = "50">raw template</textarea>
<br /><br />
<INPUT type="button" value="Click To Enter Values" onclick="getkeywords()"/>
</div>
<div align="center" id="d_div">
<br/> <br/>
</div>
</FORM>
</BODY>
</HTML>
I believe the problem is with the page is rendered into the browser that is line by line , but I cant figure out exactly what is causing this and how to fix it.
any help is appreciated.
You're using a submit button, and giving it an onclick handler. When the button is clicked, it executes your onclick handler, then proceeds to submit the form. This is why you see the value updating and then the page reloading.
If you don't want to submit the form with that button, then an <input type="submit"> is the wrong choice. Use a button instead:
<input type="button" onclick="populate_text()" />
An type=button will do nothing by default, unlike a type=submit which submits the form by default.
W3C docs for type=submit:
The input element with a type attribute whose value is "submit" represents a button for submitting a form.
W3C docs for type=button:
The input element with a type attribute whose value is "button" represents a button with no additional semantics.
That's just because of you are defined input type as "submit"
<input type = "submit" onclick="populate_text()" name = "submit" />
Whenever the action performed on submit, the page will reload. So, the default values will render again. You must to change it's type as "button".
The better use of <select> in html is, you can listen for its selected item changes like below,
<select name="element" id="rawquery" onchange="populate_text()">
<option>Select</option>
<option value = "Alpha query">Alpha</option>
<option value = "Betaquery">Beta</option>
<option value = "Gamma query">Gamma</option>
<option value = "Epsilon query">Epsilon</option>
</select>
and you can use your populate_text function to update the text area
function populate_text() {
var myvalue = document.getElementById("rawquery");
document.getElementById("mytext").innerHTML = myvalue.value;
}

Check empty field from html array in javascript

I have a simple HTML files with book seats field as array , the code below
<input type="checkbox" name="book[]" value="<?php echo $i; ?> /><?php echo $i; ?>
<input type="submit" value="BOOK" onclick = "checkIfSeatEmpty()" />
The javascript I used to validate if the field book is empty is:
var x=document.forms["bkfrm"].getElementById("chkbx").value;
//alert(x); alerts 'undefined' !
// var x=document.forms["bkfrm"].getElementById("book").length;
alert(x);
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
return TRUE;
But the above code alerts as undefined ! How can I check if the field is empty?
try like following
var x=document.forms["bkfrm"].getElementById("book").checked;
there is no such id as chkbx or book in your html code.. use the following code
Jquery
$("input[name='book']:checked").val();

Categories

Resources