I have a page where I have two columns one is Attribute name and Attribute Value. I have a button named Add Attribute Value which adds text boxes to the screen so that an Attribute Name can have multiple Attribute values. I have added the text boxes with a variable i in javascript.
I need to use the "i" variable and also access the text in the textbox using the name "'mytext'+i".
The code written is below:
<html>
<head><title>Add Attributes</title></head>
<body>
<script language="javascript">
var i = 1;
function changeIt()
{
my_div.innerHTML = my_div.innerHTML +"<br> <input type='text' name='mytext'+ i><br>"
i++;
}
</script>
<form action= "" method = "POST">
<h1 align = "center"><u>Attribute Management</u></h1>
Attribute Name Attribute Value <br>
<br><input type="text" name="attname" >
<input type="text" name="attvalue">
<input type="button" value="Add Attribute Value" onClick="changeIt()">
<div id="my_div"></div>
<b> </b><br>
<br><br><input type="submit" name = "submit" value = "Add Attribute" >
<input type="submit" name = "submit1" value = "User Application" >
</form>
</body>
</html>
<?php
if(isset($_POST['submit'])){
$att_name = $_POST['attname'];
$query_string1 = "ALTER TABLE users ADD $att_name varchar(20)";
$query_string2 = "ALTER TABLE attributes ADD $att_name varchar(20)";
$part_string = "(";
for($x = 0;$x<= i;$x++){
$att_value= $_POST['mytext'.$x];
if($x = 0){
$part_string = $part_string.$att_value;
}
else{
$part_string = ",".$part_string.$att_value;
}
}
$part_string= $part_string.")";
$query_string3 = "INSERT INTO attributes ('$att_name') VALUES '$part_string'";
$connect = mysqli_connect("localhost","root", "","nets") or die("Couldn't connect to database");
/*$query1 = mysqli_query($connect,$query_string1);
$query2 = mysqli_query($connect,$query_string2);
$query3 = mysqli_query($connect,$query_string3);*/
}
if(isset($_POST['submit1'])){
header('Location: RegisteredUsers.php');
}
?>
Get an error of "i" is not defined and "Undefined index: mytext0". I have to collect all the attribute values and fire a query with all the values from the text box together.
Please suggest.
The error of "Undefined index: mytext0" is come due to no such input field is defined, because you have initialised the i with 1 so, just make it 0.
And also you have a issue in the html, which you are adding, just change your script block with following :
var i = 1;
function changeIt()
{
my_div.innerHTML = my_div.innerHTML +"<br> <input type='text' name='mytext"+ i+"'><br>"
i++;
}
<html>
<head><title>Add Attributes</title></head>
<body>
<form action= "" method = "POST">The error of "Undefined index: mytext0" is come due to no such input field is defined, because you have initialised the i with 1 so, just make it 0.
And also you have a issue in the html, which you are adding, just change your script block with following :
<h1 align = "center"><u>Attribute Management</u></h1>
Attribute Name Attribute Value <br>
<br><input type="text" name="attname" >
<input type="text" name="attvalue">
<input type="button" value="Add Attribute Value" onClick="changeIt()">
<div id="my_div"></div>
<b> </b><br>
<br><br><input type="submit" name = "submit" value = "Add Attribute" >
<input type="submit" name = "submit1" value = "User Application" >
</form>
</body>
</html>
Related
I have these below codes which give user option to reserve a seat according to their choice. These 3 mentioned below are difficulties that I am facing I need help.
To send the total value of a variable named total from Javascript to PHP
To send the total number of selected seats which are being hold by a variable called results from Javascript to PHP
How to make a Reserve Now button inactive if a user did not select any seat from checkbox.
These below are my codes.
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Seat(s)</title>
</head>
<body>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (isset($_POST['submit'])) { //Seat Reserve
require 'action_page.php';
}
elseif (isset($_POST[''])) { //Cancel
require 'mypage.php';
}
}
//
$parameter = "this is a php variable";
echo "var myval = foo(" . parameter . ");";
?>
?>
<h2>Please choose a seat to book</h2>
<form action="index.php" method="post">
<input type="checkbox" name="vehicle" id="A1" value="100">$100<br>
<input type="checkbox" name="vehicle" id="A2" value="65"> $65<br>
<input type="checkbox" name="vehicle" id="A3" value="55"> $55<br>
<input type="checkbox" name="vehicle" id="A4" value="50"> $50<br>
<p id="demo">
Selected Seat(s)
<br>
<span id="selected-seats"></span> <!-- container for selected seats -->
<br>
Total: <span id="total-container"></span> USD
<button type="submit" class="btn btn-primary" name="submit">Reserve Now</button>
</p>
</form>
<script>
const selections = {};
const inputElems = document.getElementsByTagName("input");
const totalElem = document.getElementById("total-container");
const seatsElem = document.getElementById("selected-seats");
for (let i = 0; i < inputElems.length; i++) {
if (inputElems[i].type === "checkbox") {
inputElems[i].addEventListener("click", displayCheck);
}
}
function displayCheck(e) {
if (e.target.checked) {
selections[e.target.id] = {
id: e.target.id,
value: e.target.value
};
}
else {
delete selections[e.target.id];
}
const result = [];
let total = 0;
for (const key in selections) {
result.push(selections[key].id);
total += parseInt(selections[key].value);
}
totalElem.innerText = total;
seatsElem.innerHTML = result.join(",");
//window.alert(result); //Hold Number of Seats Selected.
//window.alert(total); //Hold Total Cost of Selected Seats.
}
var myval = foo("this is a php variable"); // I tried to take this value and output it but it didn't work out.
$.ajax({
type: 'POST',
url: 'action_page.php',
data: {'variable': total},
});
</script>
</body>
</html>
action_page.php
<html>
<head>
<title>Seats Feedback</title>
</head>
<body>
<?php
echo "<br>";
$myval = $_POST['variable'];
print_r($myval);
?>
Looking forward to hear from you guys.
When you're not doing AJAX, posting data to a PHP script the old fashioned way is a matter of:
setting the action attribute on a <form> element to point to the destination PHP script URL
ensuring your form's <input> elements contain all of the data you want to post
adding a submit button to the form
For step 1, currently, your form says to send the post request to itself. This is totally fine (you can use a <?php block ?> like you're doing to determine whether to show a success confirmation or a blank form depending on the contents of $_POST, but I'm guessing your intention is to ultimately send the data over to action_page.php. I made that the action target and removed all of the PHP from your index.
As for step 2, your total isn't currently in an <input> element and won't be posted. I created an invisible total element for this purpose: <input type="hidden" name="total" id="hidden-total" value="0"> and added a couple lines to the script to retrieve this element and set its value whenever your total is recalculated. You could combine the two total elements and style one to look and be non-editable (exercise for the reader).
Another problem relating to step 2 is that you have four different elements with the name vehicle. Only one of these name/value pairs will be posted, so I updated these elements to use unique names so they'll all be sent.
Step 3, making sure you have a submit button, you've already done successfully.
To verify it's working, you can var_dump($_POST) on the receiving PHP script to see the results of the post request or retrieve a specific value by name with e.g. $_POST['total']. At this point, your PHP script can go ahead and parse/validate/sanitize the post data, render proper response output, do a redirect, and/or do whatever else needs to be done, such as writing to a database.
Here's the full code:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Seat(s)</title>
</head>
<body>
<h2>Please choose a seat to book</h2>
<form action="action_page.php" method="post">
<input type="checkbox" name="vehicle-a1" id="A1" value="100">$100<br>
<input type="checkbox" name="vehicle-a2" id="A2" value="65"> $65<br>
<input type="checkbox" name="vehicle-a3" id="A3" value="55"> $55<br>
<input type="checkbox" name="vehicle-a4" id="A4" value="50"> $50<br>
<input type="hidden" name="total" id="hidden-total" value="0">
<p id="demo">
Selected Seat(s)
<br>
<span id="selected-seats"></span> <!-- container for selected seats -->
<br>
Total: <span id="total-container"></span> USD
<button type="submit" class="btn btn-primary" name="submit">Reserve Now</button>
</p>
</form>
<script>
const selections = {};
const inputElems = document.getElementsByTagName("input");
const totalElem = document.getElementById("total-container");
const hiddenTotalElem = document.getElementById("hidden-total");
const seatsElem = document.getElementById("selected-seats");
for (let i = 0; i < inputElems.length; i++) {
if (inputElems[i].type === "checkbox") {
inputElems[i].addEventListener("click", displayCheck);
}
}
function displayCheck(e) {
if (e.target.checked) {
selections[e.target.id] = {
id: e.target.id,
value: e.target.value
};
}
else {
delete selections[e.target.id];
}
const result = [];
let total = 0;
for (const key in selections) {
result.push(selections[key].id);
total += parseInt(selections[key].value);
}
totalElem.innerText = total;
hiddenTotalElem.value = total;
seatsElem.innerHTML = result.join(",");
}
</script>
</body>
</html>
action_page.php
<!DCOTYPE html>
<html lang="en">
<head>
<title>Seats Feedback</title>
</head>
<body>
<?php
echo "<pre style='font-size: 1.5em;'>"; // format debug post dump
var_dump($_POST);
?>
</body>
</html>
Sample output
array(5) {
["vehicle-a1"]=>
string(3) "100"
["vehicle-a3"]=>
string(2) "55"
["vehicle-a4"]=>
string(2) "50"
["total"]=>
string(3) "205"
["submit"]=>
string(0) ""
}
As before, this isn't an industrial strength example and there is plenty of room for improvement, but hopefully it does communicate the basic idea.
I am trying to make the input type text field editable on click with button but it is not working properly. tried all possible thing any suggestion please
<html><body>
<script>
$(document).ready(function()
{
$('#btnEdit').click(function()
{
$("input[name='name']").removeAttr("readonly");
});
});
</script>
<?php
require_once ('connectdb.php');
$sql = "SELECT * FROM general_information";
$result = $dbhandle->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<form>
<input type = "text" name = "name" value = <?php echo $row["email"];?> readonly>
<button class="btn btn-primary" id="btnEdit" > edit </button>
<?php } } ?>
</form>
</body></html>
There are two problems I see in the code,
Button is submitting the form and reloading the page. Use preventDefault() to override form submit.
Use prop instead of removeAttr.
$(document).ready(function(){
$('#btnEdit').click(function(e){
e.preventDefault();
$("input[name='name']").prop("readonly", false);
});
});
UPDATE from #cmorrissey comment.
In textbox, quotes are missing in the value attribute
<input type = "text" name = "name" value = "<?php echo $row["email"];?>" readonly>
Your button is posting the form thus reloading the page so Change your button and give it an onclick event function like onclick="editInputField()":
Edit
Give the input and id:
<input type = "text" id = "name" name = "name" value = <?php echo $row["email"];?> readonly>
Then your javascript function to make the input editable:
<script type="text/javascript">
function editInputField(){
document.getElementById("name").readOnly = false;
}
</script>
EDIT
I noticed you using jquery even though the question is tagged with javascript.
The reason why your code is not working has to do with:
1: The button as mentioned earlier so change it to:
Edit
2: How your targeting the input field, use the field id like this:
$("#fieldID").removeAttr("readonly");
You can use disable or readOnly attributes. Here you have two examples.
<input type="text" id="name" disabled="disabled" value="Example"/>
<input type="text" id="name2" readonly="readonly" value="Example2"/>
<button onclick="myFunction()">Click me</button>
function myFunction() {
document.getElementById("name").disabled = false;
document.getElementById("name2").readOnly = false;
}
I am hoping to hide the text field entries by showing some special character, but internally when I access the value, I want to get the entry as entered by the user.
It has to be a type="text" like
<input type="text" id="mytext" value="" size="60" maxlength="128" class="form-text mck-input-text required" />
Thanks a lot.
This is not a good idea if there is anything secure about what is typed.
A password input could be the better option.
If you want random characters displayed, you would have to do that in the script and assign the value to the obscured variable instead of 'x'. This version, for clarity, doesn't handle other key events so you can't delete any letters typed but it is just to give a few bits of usable code you could develop. The second version below allows the use of the "back" button to delete characters.
The textbox text is made white when you type into it - this will need to be made to match whatever background you use and it is still there briefly as it is typed, just not visible until it is replaced.
In your PHP page head:
<script language="javascript">
var obscured = '';
var real_value = '';
function obscure_it(real_value,ev){
document.getElementById('text_input').style.color = '#fff';
document.getElementById('real_text_hidden_input').value = document.getElementById('real_text_hidden_input').value+real_value.substr(real_value.length - 1);
obscured = window.obscured+'x'; // or + a randomly generated character
window.obscured = obscured;
document.getElementById('text_input').value = obscured;
document.getElementById('text_input').style.color = '#000';
}
function white_it(){
document.getElementById('text_input').style.color = '#fff';
}
</script>
In your form, which would have method="post":
<input type="hidden" name="real_text_hidden_input" id="real_text_hidden_input" value="" />
<input type="text" name="text_input" id="text_input" onKeyPress="white_it()" onKeyUp="obscure_it(this.value,window.event);" />
To get back the real letters typed
<?php echo htmlspecialchars($_POST['real_text_hidden_input']); ?>
A version on which the back button works to delete characters and the result submitted reflects the deletions:
<script language="javascript">
var ev = '';
var obscured = '';
var real_value = '';
function obscure_it(real_value,ev){
document.getElementById('text_input').style.color = '#fff';
document.getElementById('real_text_hidden_input').value = document.getElementById('real_text_hidden_input').value+real_value.substr(real_value.length - 1);
if(ev.keyCode != 8){
obscured = window.obscured+'x';
window.obscured = obscured;
document.getElementById('text_input').value = obscured;
}else{
document.getElementById('real_text_hidden_input').value = document.getElementById('real_text_hidden_input').value.substr(0, (document.getElementById('real_text_hidden_input').value.length-2));
}
document.getElementById('text_input').style.color = '#000';
}
function white_it(){
document.getElementById('text_input').style.color = '#fff';
}
</script>
And the form:
<form name="form" id="form" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="post">
<input type="hidden" name="real_text_hidden_input" id="real_text_hidden_input" value="" />
<input type="text" name="text_input" id="text_input" onKeyPress="white_it()" onKeyUp="obscure_it(this.value, event);" />
<input type="submit" name="sbutton" id="sbutton" value="Submit" /><br />
</form>
Click to start a new submission
<br /><?php echo htmlspecialchars($_POST['real_text_hidden_input']); ?>
This might be a useful reference for keyboard event handling: http://javascript.info/tutorial/keyboard-events
I am new to Javascript. And I am trying to create a page which is used for writing reviews. I am stuck at a certain point.
There should be a button to add a section which copies the whole sections div to allow the user to write another section.
Attached below is my code. I am using CKeditor plugin to allow the end user to format their text as they wish.
The current code , while creating a new section, doesn't allow the user to write into the text area created. Please guide me as to where I was mistaken.
<?php
include 'settings.php';
if (!isset($dbc)){
$dbc = new mysqli(DB_HOST , DB_USER , DB_PASSWORD , DB_NAME);
}
if ($dbc -> connect_error){
die ("Cannot connect to the database");
}
?>
<html>
<head>
<title>Write a new Review.</title>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
</head>
<body>
<form id = "new_review" action = "form.php" method = "post">
<div id = "header">
<h2> Header Section. </h2>
Author : <input type = "text" id = "author"> <br>
Title: <input type = "text" id = "title"> <br>
Tagline: <input type = "text" id = "tagline" > <br>
Score: <input type = "text" id = "score" > <br>
Pros: <textarea class = "ckeditor" id = "pros">
Please enter the pro's of the product here.
</textarea>
Cons: <textarea class = "ckeditor" id = "cons">
Please enter the cons of the product here.
</textarea>
Verdict:<textarea class = "ckeditor" id = "verdict">
Enter your vedict here.
</textarea>
</div>
<div id = "sections">
<h2> Sections. </h2>
<input type = "button" id="button" onclick="duplicate()">Add a section</button>
<div class = "section_base" id = "section">
Section Icon: <input type="file" id="icon" accept="image/*"> <br>
Section Title: <input type = "text" id = "section_title" > <br>
Section Text: <textarea class = "ckeditor" id = "section_text">
Enter you text here.
</textarea>
Section Score: <input type = "text" id = "section_score">
</div>
</div>
<div id = "conclusion">
<h2> Conclusion: </h2>
<textarea class = "ckeditor" id = "conclusions">
Enter your conclusion here.
</textarea>
</div>
<input type = "submit" value="submit">
</form>
<script type="text/javascript">
var i = 0;
var original = document.getElementById('section');
function duplicate() {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "section" + ++i;
// or clone.id = ""; if the divs don't need an ID
original.parentNode.appendChild(clone);
}
</script>
</body>
</html>
Below are the links from where I had the information to do what I did.
http://ckeditor.com/ckeditor_4.3_beta/samples/replacebyclass.html
How can i duplicate a div onclick with javascript?
Try your javascript as this
<script type="text/javascript">
var i = 1;
function duplicate() {
var clone = '<div class = "section_base" id = "section">Section Icon: <input type="file" id="icon" accept="image/*"> <br> Section Title: <input type = "text" id = "section_title" > <br> Section Text: <textarea id = "section_text'+i+'"> Enter you text here. </textarea>Section Score: <input type = "text" id = "section_score"> </div>';
var div = document.getElementById('sections');
var newdiv = document.createElement('div');
newdiv.innerHTML = clone;
div.appendChild(newdiv);
CKEDITOR.replace('section_text'+i);
i++;
}
</script>
Seems like CKEditor got some issues with binding the controls for dynamically added elements. You can refer to this problem which contains discussion from people facing similar issues and their solutions.
CKEDITOR inline on dynamic created element ( droppable/sortable )
Also found this jsfiddle demo, which binds CKEditor inline
CKEDITOR.inline( el.get( 0 ) );
The guy has also written a nice tutorial on how to add inline ckeditor on dynamically created elements
See if it helps...
I am trying to assign values to div by a global array (in ascending function) . but the array is always empty in ascending function. Please also mention the best practice in this case.
I wish to set an array in one function , and in the other function I wish to use the same populated array . but after entering all the values I found that page get refresh and the values assign to array and Hidden1 field are set to empty again.
<html>
<head>
<script type="text/javascript">
var array = new Array();
function get_strings(m)
{
i = 1;
do
{
var ArrayElement=prompt("Please Enter a Number");
i++;
array.push(ArrayElement);
}
while (i <= m);
document.getElementById('print').InnerHtml = array;
document.getElementById('Hidden1').value = array;
};
</script>
<script>
function ascending()
{
var x = document.getElementById('Hidden1').value;
document.getElementById('print').InnerHtml = x;
};
</script>
</head>
<body>
<h2>Enter Number of elements</h2>
<br /><br />
<form>
<input id="Hidden1" type="hidden" value="" />
<input id="num" type="text" name="elements"> <br> <input type="submit" value="Submit" text= "Take Input" onclick="get_strings(document.getElementById('num').value)">
<br />
<input type="submit" value="Ascending" text= "Ascending" onclick="ascending()">
</form>
<div id="print"></div>
</body>
</html>
Page got refreshed because you are clicking the submit button, it's just the basic desired behavior when clicking on a submit button. Which brings the question, do you intend to submit this value to the backend? If so what you need to do is to have your backend return the value after the form POST.
If you do not intend on submitting this value, then use a regular button instead of a submit button.