I have a code in which i am sending the values from a form to php page where the query lies and for sending the values i am using $.post of jquery everything is going good. I am resulting a table and a button now i want that button will work and 1 of the table column has the radio button list so i want that button will take the radio id of that perticular row on click but my button is not working so please guide me how i can do this my code is here
my javascript function
function searchDetail(searchName) {
var textName = searchName + "Text";
var inputText = $('#' + textName).val();
var formName = searchName + "Form";
if (inputText === "") {
$('#' + textName).css("border", "2px solid red").fadeIn(4000);
}
else {
$('#' + textName).css("border", "1px solid #8dd7f6").show(2000);
$('#searchBox').fadeIn(1000);
$.post('../search/delete' + searchName + '.php', $('#' + formName).serialize(), function(result) {
$('#searchBox').html(result);
})
}
}
my php code
if ($count == "0") {
echo "There is no data with $search = ".$searchKeyword;
} else {
$color = 2;
echo "<table cellspacing='0px' cellpadding='7px'><thead><tr><th>#</th><th>book Id</th><th>book Name</th><th>book Writer</th><th>book Price</th><th>Availability</th></tr></thead><tbody>";
while ($row = mysqli_fetch_array($result)) {
$checkBook = $row['booktotal'] - $row['bookremain'];
if ($checkBook == 1) {
$status = "Yes";
} else {
$status = "No";
}
if ($color % 2 == 0) {
echo "<tr class='even'><td><input type=radio name=group1 value=".$row['bookId']."></td><td>".$row['bookId']."</td><td>".$row['bookName']."</td><td>".$row['bookWriter']."</td><td>".$row['bookPrice']."</td><td>".$status."</td></tr>";
$color = $color + 1;
} else {
echo "<tr class='odd'><td><input type=radio name=group1 value=".$row['bookId']."></td><td>".$row['bookId']."</td><td>".$row['bookName']."</td><td>".$row['bookWriter']."</td><td>".$row['bookPrice']."</td><td>".$status."</td></tr>";
$color = 2;
}
}
echo "</tbody></table><br><input type=button value=Delete id=deleteButton onclick='check()'> <script type=text/javascript> function check(){alert(Hello);}</script>";
mysqli_close($con);
}
?>
my html code
<body>
<div id="deleteFormTable">
<span id="headerFont">Enter Information to Delete Book</span><br><br>
<form id="bookSearchForm" name="bookSearchForm"><label>Search Book:</label> <input type="text" id="bookSearchText" name="bookSearchText"/> <select id="bookSearchOption" name="bookSearchOption"><option id="bookSearchId">Id</option><option id="studentSearchName">Name</option></select> <input type="button" value="Search" id="bookSearch" name="bookSearch" onclick="searchDetail(this.id)"></form>
</div>
<div id="searchBox">
<center><div id="searchLoadBox"><img src="../images/loadings.gif" alt="..."></div></center>
</div>
</body>
OK, I think I know what you are asking.
You have a list of items with radio boxes next to them, once the user clicks one and then clicks the button, you want the "value" tied to that radio button.
If that is the case, you can use this to find the value of the "Checked" radio group.
$("#deleteButton").click(function()
{
var bookId = $("input[#name='group1']:checked").val();
}
Related
How to insert dynamically generated field values to backend using mysql.
Im trying to add rows with text box and drop down using jquery and auto saving
the field values at regular intervals.
So i need to fetch the ids of the textboxes and drop down, but currently i get the id of only the first text box and drop down.
$(function() {
$("#btnAdd").bind("click", function() {
AddControl();
});
$("#btnGet").bind("click", function() {
var values = "";
$("input[name=DynamicTextBox]").each(function() {
values += $(this).val() + "\n";
});
alert(values);
});
$("body").on("click", ".remove", function() {
$(this).closest("div").remove();
var i = 1;
var Ids = [];
$('[id*=ddl]').each(function() {
$(this).attr("id", "ddl" + i);
Ids.push(i);
i++;
});
$('[id*=hfDDLId]').val(parseInt($('[id*=hfDDLId]').val()) - 1);
var resultIds = Ids.join(',');
$('[id*=hfDropDownIds]').val(resultIds);
});
});
function AddControl() {
var Id = parseInt($('[id*=hfDDLId]').val()) + 1;
var ddlId = "ddl" + (Id);
var div = $("<div />");
div.html(getDropDownList(ddlId, ddlId));
div.append(GetDynamicTextBox(''));
$("#TextBoxContainer").append(div);
$('[id*=hfDDLId]').val(Id);
var previousDropDownId = $('[id*=hfDropDownIds]').val();
if (previousDropDownId != '') {
$('[id*=hfDropDownIds]').val(previousDropDownId + ',' + Id);
} else {
$('[id*=hfDropDownIds]').val(Id);
}
return false;
}
function getDropDownList(name, id) {
var combo = $("<select></select>").attr("id", id).attr("name", name).attr("runat", "server").attr("class", "class").attr("required", "required");
combo.append("<option value=" + "" + ">" + "Select Category" + "</option>");
combo.append("<option value=" + "1" + ">" + "1" + "</option>");
combo.append("<option value=" + "2" + ">" + "2" + "</option>");
combo.append("<option value=" + "3" + ">" + "3" + "</option>");
return combo;
}
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" id="ingr_name" type="text" value = "' + value + '" required/> ' + '<input name = "DynamicTextBox" type="text" value="' + value + '" required/> ' + '<input type="button" value="Remove" class="remove" />'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" runat="server">
<div>
<input id="btnAdd" type="button" value="Add" />
<br/>
<br/>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br/>
<input type="hidden" id="hfSelectedValue" runat="server" />
<input type="hidden" id="hfDropDownIds" value="" runat="server" />
<input id="btnGet" type="button" value="Get Values" />
<input type="hidden" id="hfDDLId" value="0" />
</div>
</form>
Code for inserting in the backend
Assunimg i have given the id for the text box as 'ingr_name' im posting the same as :
<?php
$con=mysqli_connect("localhost","root","pass","DB");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['txt_area']) && $_POST['txt_area'] != '') {
$ingr_name = mysqli_real_escape_string($con,$_POST['ingr_name']);
$qry = "Select count(*) as cnt from table";
$res = mysqli_query($con,$qry);
$row = mysqli_fetch_array($res);
if ($row['cnt'] == 0) {
$qry_ins = 'my insert query';
}
?>
#SachinSachin if you want to insert only one text box value try the below code
function insert_data(){
var url = "insert.php";
$.ajax({
url : url,
type: "POST",
data: $('#formid').serialize(),
success: function(data)
{
alert(data);
}
});
}
call this function on submit button and in insert.php you get the values using post method as usual and insert them in mysql. if it is success print echo "inserted"; else print echo "failed"; you will get this status in alert message in above insert_data() function. Here i assumed you are using php as backend if not use your language with same process.
I have some javascript that pulls some mysql data using xmlhttp.responsetext. I've been using it to populate form data for a drop down box and it has been working well. However, I have a need to add a second dropdown menu in the form and it is not working right.
What is happening is both dropdowns are populating with data from 2 different tables when each dropdown should only be getting its data from its respective table.
Could use some help figuring this out, thanks.
Here is the javascript code.
<script type="text/javascript">
var counter = 1;
function addInput(div){
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
var newdiv = document.createElement(div);
newdiv.innerHTML = "<table><tr><td>Line Item " + (++counter) + "</td></tr><tr><td width='190'>Item: <select name='item[]'>" + xmlhttp.responseText.split( "[BRK]" ) + "</select></td><td width='100'>Qty: <input name='quantity[]' type='text' size='2' /></td><td width='500'>Description: <input name='description[]' type='text' size='60' /></td><td width='150'>Amount: <input name='amount[]' type='text' size='6' /></td><td>Tax Rate: <select name='taxrate[]'>" + xmlhttp.responseText.split( "BRK" ) + "</select></td></tr></table><br />";
}
document.getElementById(div).appendChild(newdiv);
}
xmlhttp.open("GET", "dropdownquery.php", false);
xmlhttp.send();
}
</script>
And here is php.
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
$result = mysql_query("SELECT * FROM salesitem");
$result2 = mysql_query("SELECT * FROM salestax");
while($row = mysql_fetch_array($result)) {
echo "<option value=\"".$row['name']."\">".$row['name']."</option>";
}
echo "[BRK]";
while($row2 = mysql_fetch_array($result2)) {
echo "<option value=\"".$row2['amount']."\">".$row2['name']."</option>";
}
echo "[BRK]";
?>
When you split a string, you get an array. I suppose you want to do this:
var splitResponse = xmlhttp.responseText.split( "[BRK]" );
var firstDropdownContent = splitResponse[0];
var secondDropdownContent = splitResponse[1];
Then use the two new variables to build your HTML.
I have an html table having n rows. Each row has a name and 2 radio buttons. If I click a radio button, I want to show an alert that states the count of votes. How should I pass the name of the radio button to the Javascript and how should I do the counting?
Here's the PHP part:
list($cols,) = $xlsx->dimension();
$var=0;
foreach( $xlsx->rows() as $k => $r) {
$var++;
echo '<tr>';
echo '<td>'.$k.'</td>';
echo '<td>'.( (isset($r[0])) ? $r[0] : ' ' ).'</td>';
echo '<td><Input type = "Radio" Name ="vote'.$var.'" value= "pacada" onclick = "AddPacada()"></td>';
echo '<td><Input type = "Radio" Name ="vote'.$var.'" value= "toledo" onclick = "AddToledo()"></td>';
echo '</tr>';
and here's the Javascript part:
function AddPacada(){
if(document.tally.pacada.checked == true){
alert("You have clicked on Pacada.");
}
}function AddToledo(){
if(document.tally.toledo.checked == true){
alert("You have clicked on Toledo.");
}
}
You just pass it as an argument:
... onclick = "AddPacada(this)" ...
^^^^
/* And in your function: */
function AddPacada(radio) {
alert(radio.value);
}
Change your onclick in your PHP code to onclick=tally(this)
Then this javascript will alert the totals currently selected:
<script>
var selections = new Array(); //keep track of the selections
function tally(e) {
val = e.value;
name = e.name;
selections[name] = val; //an associative array or "hash"
var totals = new Array();
for (var key in selections) {
var selection=selections[key];
if(totals[selection] == undefined) { //set to 1 if not already initialized
totals[selection] = 1;
} else {
totals[selection] += 1;
}
}
alert(val + " has been selected " + totals[val] + " times");
}
</script>
Style-wise, I would try to emit the following HTML:
<input type="radio" name="var1" value="a" onclick="tally(this)"/>
<input type="radio" name="var1" value="b" onclick="tally(this)"/>
<input type="radio" name="var2" value="a" onclick="tally(this)"/>
<input type="radio" name="var2" value="b" onclick="tally(this)"/>
Note the spacing and case.
I have a piece of code below where it determines which assessment the user is in and the assessment number the user is currently on:
<?php echo $sessionMinus ?> OF <?php echo $_SESSION['initial_count'] ?>
So on the browser this could read for example:
1 OF 4
Now below I have a submit button:
<input id="addQuestionBtn" name="addQuestion" type="button" value="Add Question" onClick="insertQuestion(this.form)" />
Now if the user clicks on the button, it will show a confirmation box and if the user clicks OK, for the confirmation, then it will submit the page and what is suppose to happen is that it adds a number to the assessment to indicate that the user is on the next assessment.
SO FOR EXAMPLE:
If it says this on the page:
1 OF 4
If the user submits the page and confirms, then it should now say this:
2 OF 4
This is because the user is on the next assessment now.
But the problem is that it is not adding the number at all when the user submits the page. It just stays at '1' and doesn't add up. So instead of doing the above it is doing the below:
If it says this on the page:
1 OF 4
If the user submits the page and confirms, then it still says:
1 OF 4
This is obviously incorrect.
I have tested my code and what I have found is that if there is that the jquery validation() is causing the number to not add up and stay at '1'. But my question is that how come this jquery function is causing this to happen?
Below is the jquery validation() function:
function validation() {
var _qid = "";
var _msg = "";
var alertValidation = "";
// Note, this is just so it's declared...
$("tr.optionAndAnswer").each(function() {
});
if (alertValidation != "") {
alert(_msg + alertValidation);
return false;
}
return true;
}
Below is relevant code so you know what the code is:
<?php
session_start();
if(isset($_POST['sessionNum'])){
//Declare my counter for the first time
$_SESSION['initial_count'] = $_POST['sessionNum'];
$_SESSION['sessionNum'] = intval($_POST['sessionNum']);
$_SESSION['sessionCount'] = 1;
}
elseif (isset($_POST['submitDetails']) && $_SESSION['sessionCount'] < $_SESSION['sessionNum']) {
$_SESSION['sessionCount']++;
}
$sessionMinus = $_SESSION['sessionCount'];
if ($sessionMinus == $_SESSION['initial_count']){
$action = 'create_session2.php';
}elseif($sessionMinus != $_SESSION['initial_count']){
$action = $_SERVER['PHP_SELF'];
}
?>
<script type="text/javascript">
function validation() {
var _qid = "";
var _msg = "";
var alertValidation = "";
// Note, this is just so it's declared...
$("tr.optionAndAnswer").each(function() {
});
if (alertValidation != "") {
alert(_msg + alertValidation);
return false;
}
return true;
}
function showConfirm(){
var confirmMsg=confirm("Make sure that your details are correct, once you proceed after this stage you would not be able to go back and change any details towards Questions, Options and Answers for your Session." + "\n" + "\n" + "Are you sure you want to Proceed?" + "\n" );
if (confirmMsg==true)
{
submitform();
}
}
function submitform()
{
var fieldvalue = $("#QandA").val();
$.post("insertQuestion.php", $("#QandA").serialize() ,function(data){
var QandAO = document.getElementById("QandA");
QandAO.submit();
});
alert("Your Details for this Session has been submitted");
}
</script>
</head>
<body>
<form id="QandA" action="<?php echo htmlentities($action); ?>" method="post">
<h1><?php echo $sessionMinus ?> OF <?php echo $_SESSION['initial_count'] ?></h1>
<div id="detailsBlock">
<table id="questionBtn" align="center">
<tr>
<th>
<input id="addQuestionBtn" name="addQuestion" type="button" value="Add Question" onClick="insertQuestion(this.form)" />
</th>
</tr>
</table>
</div>
<hr/>
<div id="details">
<table id="qandatbl" align="center">
<thead>
<tr>
<th class="question">Question</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<p><input id="submitBtn" name="submitDetails" type="submit" value="Submit Details" onClick="myClickHandler(); return false;" /></p>
</form>
<script type="text/javascript">
function myClickHandler(){
if(validation()){
showConfirm();
}
}
</script>
UPDATE:
Below is the code of in the insertQuestion() function:
function insertQuestion(form) {
var $tbody = $('#qandatbl > tbody');
var $tr = $("<tr class='optionAndAnswer' align='center'>");
var $image = $("<td class='image'></td>");
var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='return imageClickHandler(this);' class='imageuploadform' >" +
"<p class='imagef1_upload_process' align='center'>Loading...<br/><img src='Images/loader.gif' /><br/></p><p class='imagef1_upload_form' align='center'><br/><label>" +
"Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><br/><label class='imagelbl'>" +
"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>" +
"<iframe class='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px;solid;#fff;'></iframe></form>");
$image.append($fileImage);
$tr.append($image);
$tbody.append($tr);
}
I think you want to check if sessionCount is NOT set (!isset). Try adjusting your code like this:
if(!isset($_POST['sessionCount'])){
//Declare my counter for the first time
$_SESSION['initial_count'] = $_POST['sessionNum'];
$_SESSION['sessionNum'] = intval($_POST['sessionNum']);
$_SESSION['sessionCount'] = 1;
}
elseif (isset($_POST['submitDetails']) && $_SESSION['sessionCount'] < $_SESSION['sessionNum']) {
$_SESSION['sessionCount']++;
}
I want to insert values from another form field in one text area. There are multiple fields, each placed in different forms with different submit buttons. Whenever the button is clicked, the values in that form should be inserted into the text area.
The fields are generated in an array. I have assigned the same id name for every field. This is to make every field's values belong to that textarea. My problem is, only the first field insert its value into the textarea when I click its button.Other fields not working. How could I fix this?
Here is the code:
<script type="text/javascript">
window.onload = function() {
btn1 = document.getElementById("btnInsertText1");
myText1 = document.getElementById("myTextArea1");
text1 = document.getElementById("textToInsert1");
btn1.onclick = function(){
insertAtCursor(myText1, text1.value);
}
}
function insertAtCursor(myField, myValue) {
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
}
else {
myField.value += myValue;
}
}
</script>
<textarea id="myTextArea1" name="update" cols="85" rows="22">
Testing. Values from another field will be inserted here.
</textarea>
<?php
$ref = "
SELECT *
FROM reftext1_objective
WHERE projectid='$id'";
$refresult = mysql_query($ref);
while($row = mysql_fetch_array($refresult))
{?>
<form>
<input id="textToInsert1" type="text" value="<?php echo $row[$text];?>" readonly="true">
<input type="button" id="btnInsertText1" value="<<" />
</form><br><?php
}
As stated in my comment on the question, the problem is due to the duplicated element ids in the loop in your PHP code. To fix it, try this:
<script type="text/javascript">
$(function() {
var textarea = document.getElementById("myTextArea1");
$(".button").click(function() {
var $parentForm = $(this).closest("form");
var text = $(".insert-text", $parentForm).val();
insertAtCursor(textarea, text);
});
});
function insertAtCursor(myField, myValue) {
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
}
else {
myField.value += myValue;
}
}
</script>
<textarea id="myTextArea1" name="update" cols="85" rows="22">
Testing. Values from another field will be inserted here.
</textarea>
<?php
$ref = "SELECT * FROM reftext1_objective WHERE projectid = '$id'";
$refresult = mysql_query($ref);
while ($row = mysql_fetch_array($refresult))
{ ?>
<form>
<input class="insert-text" type="text" value="<?php echo $row[$text];?>" readonly="true">
<input type="button" class="button" value="<<" />
</form><br>
<?php }
?>
Example fiddle