passing value from modal to main form - javascript

I have a contact script as follows:
<?php
Session_start();
if (!isset($_SESSION['username'])){
header("Location:../index.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test Modal</title>
<link rel="stylesheet" href="../css/style.css">
<link href="../libraries/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="../libraries/css/bootstrap-datetimepicker.min.css" rel="stylesheet" media="screen">
<link rel="stylesheet" href="../libraries/css/jquery-ui.css">
<script src="../libraries/js/jquery-1.10.2.js"></script>
<script src="../libraries/js/jquery-ui.js"></script>
<script type="text/javascript" src="../libraries/date/jquery/jquery-1.8.3.min.js" charset="UTF-8"></script>
<script type="text/javascript" src="../libraries/date/bootstrap/js/bootstrap.min.js"></script>
<script>
// Get Organization ID
function getOrganizationID(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getorganizationid.php?q="+str,true);
xmlhttp.send();
}
}
// Auto Complete for Organization field
$(function() {
$( "#skills" ).autocomplete({
source: '../libraries/organization/search.php'
});
});
</script>
</head>
<script type="text/javascript">
//
function chName(value) {
var val_fname = document.getElementById('fname').value;
var val_lname = document.getElementById('lname').value;
var val_fullname = val_fname + ' ' + val_lname;
document.getElementById('org').value = val_fullname;
}
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
<div id="main">
<form name="create" id="create" method="post" action="do_create.php">
<table style="width:100%;font-weight:bold;">
<tr>
<td>First Name</td>
<td><input id="fname" name="fname" type="text" required>*</td>
<td>Last Name</td>
<td><input id="lname" name="lname" type="text" onblur="chName(this.value)" required>*</td>
</tr>
<tr>
<td>Phone</td>
<td><input name="phone" type="text" required>*</td>
<td>Email</td>
<td><input name="email" type="text" required>*</td>
</tr>
<tr>
<td>Mobile Phone</td>
<td><input name="mobile" type="text"></td>
<td>Organization</td>
<td>
<input id="skills" type="text" name="skills" value="" onblur="getOrganizationID(this.value);return false;">
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">+</button>
<div id="txtHint" style="width:1px;height:1px;">
<input id="organization_id" name="organization" type="hidden" readonly>
</div>
<input id="org1" type="hidden" name="ocname" value="<?php echo $hash;?>">
</td>
</tr>
</table>
</form>
</div>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<script type="text/javascript">
function chOrg(value) {
var val_oname = document.getElementById('oname').value;
document.getElementById('skills').value = val_oname;
}
</script>
<form name="addorganization" id="addorganization" method="post" action="add_organization.php" target="myIframe" onsubmit="chOrg(this.value)">
<div id="headsum">
<strong>Create Organization</strong>
<input style="float:right;" name="add_organization" type="submit" value="SAVE">
</div>
<table style="width:100%;font-weight:bold;text-align:left;">
<tr>
<td>Organization Name</td>
<td><input name="oname" type="text" required>*</td>
<td>Contact Name</td>
<td><input id="org" type="text" name="org" value="" readonly>*
<input id="org1" type="hidden" name="ocname" value="<?php echo $hash;?>"></td>
</tr>
<tr>
<td>Phone</td>
<td><input name="ophone" type="text" required>*</td>
<td>Email</td>
<td><input name="oemail" type="text" required>*</td>
</tr>
</table>
</form>
<iframe style="display:none;" src="" name="myIframe" id="myIframe">
</iframe>
</div>
</div>
when I click the button beside the organization filed, will appear a popup (modal) to add an organization.
organization contact name on the form is automatically populated with the name that fill in the main form.
What I want to ask here is:
how after the organization form stored, the name of the organization and hash on the main form will automatically be filled with the names and hashes saved from earlier organizational form, because of what I have tried has not succeeded

Hello Take one hidden field in main form. so after submitting the form pass that value to the hidden field.
Hope it helps !!

Related

Using javascript for form validation in HTML

I have been looking at some examples of form validation, where an invalid input will stop the user before proceeding to the next page. The way I have seen this done many times is using the event.preventDefault() function, but it just doesn't seem to be working for me. I'm not sure if the javascript function is wrong, or maybe it is just not being read at all. When I send in an invalid input it goes through to the next page anyway.
Here is my HTML code:
Header:
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="3.css"/>
<script type="text/javascript" src="3.js"></script>
<title>Login</title>
Body:
<section>
<h2>Login</h2>
<div id="loginInfo">
<form id="loginForm" method="post" action="nextpage.php" enctype="multipart/form-data">
<table id="loginTable">
<tr>
<td>
<input type="text" class="loginInput" id="loginEmail" name="loginEmail" placeholder="Email">
</td>
</tr>
<tr>
<td><label id="emailError" class="errorMsg"></label></td>
</tr>
<tr>
<td>
<input type="password" class="loginInput" id="loginPassword" name="loginPassword" placeholder="Password">
</td>
</tr>
<tr>
<td><label id="passError" class="errorMsg"></label></td>
</tr>
<tr>
<td></br><input type="submit" name="submit" id="loginSubmit" value="Login"></td>
</tr>
</table>
</form>
</div>
</section>
and here is the referenced 3.js code:
document.getElementById("loginForm").addEventListener("submit", loginFunction, false);
function loginFunction(event)
{
var valid= true;
var elements= event.currentTarget;
var email= elements[0].value;
var pass= elements[1].value;
var regexEmail= /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
var regexPass= /^(\S*)?\d+(\S*)?\W+$/;
var emailError= document.getElementById(emailError);
var passError= document.getElementById(passError);
if (email == null || email == ""){
emailError.innerHTML= "Email is empty";
valid= false;
}
else if (regexEmail.test(email) == false){
emailError.innerHTML= "Incorrect Email format";
valid= false;
}
if (pass == null || pass == ""){
passError.innerHTML= "Password is empty.";
valid = false;
}
else if (regexPass.test(pass) == false) {
passError.innerHTML= "Incorrect password format";
valid = false;
}
else if (pass.length < 8){
passError.innerHTML= "Password is too short, must be 8+ characters";
valid= false;
}
if (valid == false){
event.preventDefault();
}
}
Can anyone explain where i've made my error?
This should do the trick:
<section>
<h2>Login</h2>
<div id="loginInfo">
<form id="loginForm" method="post" action="nextpage.php" enctype="multipart/form-data">
<table id="loginTable">
<tr>
<td>
<input type="text" class="loginInput" id="loginEmail" name="loginEmail" placeholder="Email">
</td>
</tr>
<tr>
<td><label id="emailError" class="errorMsg"></label></td>
</tr>
<tr>
<td>
<input type="password" class="loginInput" id="loginPassword" name="loginPassword" placeholder="Password">
</td>
</tr>
<tr>
<td><label id="passError" class="errorMsg"></label></td>
</tr>
<tr>
<td></br><input type="button" name="submit" id="loginSubmit" value="Login"></td>
</tr>
</table>
</form>
</div>
</section>
And this:
document.getElementById('loginSubmit').addEventListener('click',loginFunction,false);
function loginFunction()
{
var valid=true;
var elements=event.currentTarget;
var email=elements[0].value;
var pass=elements[1].value;
var regexEmail=/^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
var regexPass=/^(\S*)?\d+(\S*)?\W+$/;
var emailError=document.getElementById(emailError);
var passError=document.getElementById(passError);
if(email==null||email=='')
{
emailError.innerHTML='Email is empty';
valid=false;
}
else if(regexEmail.test(email)==false)
{
emailError.innerHTML='Incorrect Email format';
valid=false;
}
if(pass==null||pass=='')
{
passError.innerHTML='Password is empty.';
valid=false;
}
else if(regexPass.test(pass)==false)
{
passError.innerHTML='Incorrect password format';
valid=false;
}
else if(pass.length<8)
{
passError.innerHTML='Password is too short, must be 8+ characters';
valid=false;
}
if(!valid)
{
return
}
document.getElementById('LoginForm').submit();
}

Prevent form submission by checking every dynamically created text boxes are empty

Here I am trying to check each and every dynamically created textboxes whether it is empty or not before the form submission.
Here is the HTML code,
<form>
<table class="table table-hover table-white">
<thead>
<tr>
<th class="col-sm-1">Test ID</th>
<th class="col-md-6">Test Name</th>
<th style="width:100px;">Amount</th>
<th> Action</th>
</tr>
</thead>
<tbody id="rows">
<tr>
<td> <input class="form-control test_id" type="text" style="width:200px" id="test_id" onblur="checkname(this);" onkeyup="checkname(this);" onchange="checkname(this);"> </td>
<td> <input type="text" style="width:300px" class="form-control test_name" readonly="" id="test_name" onblur="checkname();" onkeyup="checkname();" onchange="checkname();"></td>
<td> <input type="text" style="min-width:100px" class="form-control amount" name="amount" readonly=""> </td>
<td><center> <i class="fa fa-plus"></i> </center> </td>
</tr>
</tbody>
</table>
<span id="test_id_info" class="info text-danger"></span>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Other Information</label>
<textarea class="form-control" id="description"></textarea>
</div>
</div>
</div>
<div class="text-center m-t-20">
<input type="button" class="btn btn-primary submit-btn" name="pay"value="Generate Invoice" id="pay">
</div>
</form>
Here is the Ajax code
$(document).ready(function(){
var count=0;
$(document).on('click','#add',function() {
count++;
var html= '';
html += '<tr id="trrows">';
html += '<td id="testid"> <input id="test_id" class="form-control test_id" type="text" style="width:200px" onblur="checkname(this);" onkeyup="checkname(this);" onchange="checkname(this);" onblur="sum(this);" onkeyup="sum(this);" onchange="sum(this);"> </td>';
html += '<td id="testname"> <input id="test_name" type="text" style="width:300px" class="form-control test_name" readonly="" onblur="checkname();" onkeyup="checkname();" onchange="checkname();"> </td>';
html += '<td id="amounts"> <input id="amount" name="amount" type="text" style="min-width:150px" class="form-control amount" readonly="" > </td>';
html += '<td><center> <i class="fa fa-trash-o"></i></center> </td>';
html += '</tr>';
$('#rows').append(html);
});
$(document).on('click','.remove',function() {
$(this).closest("#trrows").remove();
});
});
// generate bill
$(document).on('click', '#pay', function () {
var test_id = new Array();
$('input[id="test_id"]').each(function() {
test_id.push(this.value);
});
var amount = new Array();
$('input[name="amount"]').each(function() {
amount.push(this.value);
});
var p_id = $('#p_id').val();
var pres_id = $('#pres_id').val();
var description=$('#description').val();
var valid;
valid = validateContact();
if (valid) {
swal({
title: "Are you sure?",
text: "You wanna proceed this Payment!",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn-success",
confirmButtonText: "Yes, Proceed It!",
closeOnConfirm: false
},
function(isConfirm){
if (!isConfirm) return;
$.ajax({
url: "testquery/test_payments.php", // Url to which the request is send
method: "POST", // Type of request to be send, called as method
data: {
'test_id': test_id,
'amount': amount,
'p_id': p_id,
'pres_id': pres_id,
'description':description
},
success: function (data) {
if (data == 'Password Changed') {
swal("Success", "Invoice has been Generated :)", "success");
} else {
swal("Sorry", "Something Went Wrong. Please try again later:(", "error");
}
},
error: function (data) {
//other errors that we didn't handle
swal("Sorry", "Failed to Proceed. Please try later :(", "error");
}
});
});
};
// check validations
function validateContact() {
var valid = true;
$(".demoInputBox").css('background-color', '');
$(".info").html('');
if (!$("#test_id").val()) {
$("#test_id_info").html("(Required)");
$("#test_id").css('background-color', '#FFFFDF');
valid = false;
}
return valid;
}
});
I want to check the test_id textbox is empty. Before dynamically generating the textboxes there, already there is a row of textboxes including test_id textbox. My problem is, before generated, it check the textbox as empty or not by using function, but after generated it does not check. I don't know where I went wrong.
Please help me may highly appreciated.
Rather than using the elementID use class name to get the collection of elements and iterate through them. the problem we have here is all input have the same id so jquery will return the first element it finds and ignore the rest since with ID we assume that it is unique throughout the DOM
function checkname(el){
}
$(document).ready(function(){
var count=0;
$(document).on('click','#add',function() {
debugger;
count++;
var html= '';
html += '<tr id="trrows">';
html += '<td id="testid"> <input id="test_id" class="form-control test_id" type="text" style="width:200px" onblur="checkname(this);" onkeyup="checkname(this);" onchange="checkname(this);" onblur="sum(this);" onkeyup="sum(this);" onchange="sum(this);"> </td>';
html += '<td id="testname"> <input id="test_name" type="text" style="width:300px" class="form-control test_name" readonly="" onblur="checkname();" onkeyup="checkname();" onchange="checkname();"> </td>';
html += '<td id="amounts"> <input id="amount" name="amount" type="text" style="min-width:150px" class="form-control amount" readonly="" > </td>';
html += '<td><center> <i class="fa fa-trash-o"></i></center> </td>';
html += '</tr>';
$('#rows').append(html);
});
$(document).on('click','.remove',function() {
$(this).closest("#trrows").remove();
});
});
// generate bill
$(document).on('click', '#pay', function () {
var test_id = new Array();
$('input[id="test_id"]').each(function() {
test_id.push(this.value);
});
var amount = new Array();
$('input[name="amount"]').each(function() {
amount.push(this.value);
});
var p_id = $('#p_id').val();
var pres_id = $('#pres_id').val();
var description=$('#description').val();
var valid;
valid = validateContact();
if (valid) {
alert('invoice generated')
};
// check validations
function validateContact() {
debugger;
var valid = true;
$(".demoInputBox").css('background-color', '');
$(".info").html('');
//list of test_id inputs
var testIdList =
document.getElementsByClassName('test_id')
for(let i= 0 ; i<testIdList.length; i++){
if (!testIdList.item(i).value) {
$("#test_id_info").html("(Required)");
$("#test_id").css('background-color', '#FFFFDF');
valid = false;
}
}
return valid;
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<table class="table table-hover table-white">
<thead>
<tr>
<th class="col-sm-1">Test ID</th>
<th class="col-md-6">Test Name</th>
<th style="width:100px;">Amount</th>
<th> Action</th>
</tr>
</thead>
<tbody id="rows">
<tr>
<td> <input class="form-control test_id" type="text" style="width:200px" id="test_id" onblur="checkname(this);" onkeyup="checkname(this);" onchange="checkname(this);"> </td>
<td> <input type="text" style="width:300px" class="form-control test_name" readonly="" id="test_name" onblur="checkname();" onkeyup="checkname();" onchange="checkname();"></td>
<td> <input type="text" style="min-width:100px" class="form-control amount" name="amount" readonly=""> </td>
<td><center> <i class="fa fa-plus"></i> </center> </td>
</tr>
</tbody>
</table>
<span id="test_id_info" class="info text-danger"></span>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Other Information</label>
<textarea class="form-control" id="description"></textarea>
</div>
</div>
</div>
<div class="text-center m-t-20">
<input type="button" class="btn btn-primary submit-btn" name="pay"value="Generate Invoice" id="pay">
</div>
</form>
Use class, name or other attributes instead id, because you have a several elements with the same ids - it's always create problems. If you need check inputs with class "text_id" before submit try to change validation function
function validateContact() {
var valid = true;
$(".demoInputBox").css('background-color', '');
$(".info").html('');
$('.text_id').map(function(i, el){
if(!$(el).val() || $(el).val().trim() == '') {
valid = false;
$("#test_id_info").html("(Required)");
$(el).css('background-color', '#FFFFDF');
}
});
return valid;
}

Delete records from a table (Firebase)

I do not know how to delete the specific record when I click the img on the right
I want it to work like that:
Also I put an img for delete the specific record but I do not know how to add an event listener on img in the JS to delete the row and the record. Also, when I insert data in the DB I add the UID of the specific object for the delete purposes.
HTML code
<html>
<head>
<title>Fall-App Admin Panel</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<LINK rel="stylesheet" href="style.css" type="text/css" media="all">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase.js"></script>
</head>
<body>
<div class="cabecera">
</div>
<div class="cuerpo">
<div class="botones">
<table style="background-color:grey;height:100%; width:99%" border="10" id="logout">
<tr><td>Επεξεργασία Κοινωνικών Υπηρεσιών</td></tr>
<tr><td>Αποσύνδεση</td></tr>
</table>
</div>
<div class="welcome">
<div class="container">
<!--<form>
<input class="input" type="text" id="searchTxt" placeholder="Αναζήτηση για ...">
<input class="submit" type="submit" id="searchBtn" value="Εύρεση">
</form>-->
<input type="text" placeholder="Επιβεβαίωση Κωδικού" name="rePsw" id="rePswReg" required>
<button type="submit" id="searchBtn">Εγγραφή</button>
<table class="searchTable" style="width:100%">
<thead>
<tr>
<td>Name Of Service</td>
<td>Address</td>
<td>Postal</td>
<td>City</td>
<td>Phone</td>
<td>Delete</td>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
</div>
<form id="submitForm">
Name Of Service:<br>
<input type="text" name="name" id="nameDB"><br>
Address:<br>
<input type="text" name="address" id="addressDB">
Postal:<br>
<input type="text" name="postal" id="postalDB">
City:<br>
<input type="text" name="city" id="cityDB">
Phone:<br>
<input type="text" name="phone" id="phoneDB">
<button type="submit" id="btnInsert">Inster</button>
</form>
<script src="registered.js"></script>
</div>
</div>
<div class="pie">
</div>
</body>
</html>
JS code
(function() {
//initialize Firebase
var config = {
};
firebase.initializeApp(config);
const searchBtn = document.getElementById('searchBtn');
//const searchTxt = document.getElementById('searchTxt');
var messagesRef2 = firebase.database().ref().child('socialServices');
var counter=-1;
//bring all to the table
var messagesRef2 = firebase.database().ref().child('socialServices');
messagesRef2.on("child_added", snap => {
counter++;
var name=snap.child("name").val();
var address=snap.child("address").val();
var postal=snap.child("postal").val();
var city=snap.child("city").val();
var phone=snap.child("phone").val();
$("#tableBody").append("<tr><td>" + name + "</td><td>" + address + "</td><td>" +
postal + "</td><td>" + city + "</td><td>" + phone + "</td><td>" + "<img src='http://icons.iconarchive.com/icons/hopstarter/button/16/Button-Close-icon.png' id='Img'>" + "</td></tr>");
});
//regerence messages collection
var messagesRef = firebase.database().ref('socialServices');
//listen for form submit
document.getElementById('submitForm').addEventListener('submit', submitForm);
//submit form
function submitForm(e){
e.preventDefault();
//get values
var name=getInputVal('nameDB');
var address=getInputVal('addressDB');
var postal=getInputVal('postalDB');
var city=getInputVal('cityDB');
var phone=getInputVal('phoneDB');
//save message
saveMessage(name, address, postal, city, phone);
}
//function to get form values
function getInputVal(id){
return document.getElementById(id).value;
}
//save message to firebase
function saveMessage(name, address, postal, city, phone){
var newMessageRef = messagesRef.push();
newMessageRef.set({
id: newMessageRef.key,
name: name,
address: address,
postal: postal,
city: city,
phone: phone
});
}
}());

“Undefined index: itemdetails” when sending JSON object from JavaScript to PHP

Upon entering the quantity of an item and clicking the Add to Cart button the toShoppingCart() method is executed. This method will get the values of labels and text fields and insert them into a JSON object and pass it to the Order.php file.
When sending the JSON object from JavaScript to PHP it returns an error:
Undefined index: itemdetails
Onearlist.html:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="Order.php">
<table border="2">
<tr>
<td>
<div style="padding: 40px"><label id="id">001</label> <label id="name">SMS Audio street by 50 on-ear wired</label> <label id="price">179.00$</label> Qty <input type="text" id="qtytxt"><input type="button" value="Add to Cart" onclick="toShoppingCart()" /></div>
</td>
</tr>
<tr>
<td>
<div style="padding: 40px"><label id="id">002</label><label id="name">Beats Solo2 on-ear wired</label> ,<label id="price">199.00$</label> Qty<input type="text" id="qtytxt"><input type="button" value="Add to Cart" onclick="toShoppingCart()" /></div>
</td>
</tr>
<tr>
<td>
<div style="padding: 60px"></div>
</td>
</tr>
</table>
<input type="submit" value="Check Out">
</form>
<script type="text/javascript">
function toShoppingCart() {
console.log("toShoppingCart");
var id = document.getElementById("id").innerHTML;
var name = document.getElementById("name").innerHTML;
var qty = document.getElementById("qtytxt").value;
var price = parseFloat(document.getElementById("price").innerHTML);
console.log(id);
console.log(name);
console.log(qty);
console.log(price);
var request;
var itemdata = {
"id": id,
"name": name,
"qty": qty,
"price": price
};
open("Order.php", "window1");
send({
itemdetails: JSON.stringify(itemdata)
});
}
</script>
</body>
</html>
Order.php:
<?php
$data = json_decode($_GET['itemdetails']);
echo $data;
?>
To send ajax request do this:
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
var DONE = this.DONE || 4;
if (this.readyState === DONE){
alert(request.responseText); // get response form the server
}
};
request.open('GET', 'Order.php?itemdetails='+JSON.stringify(itemdata), true);
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
request.send(null);
or if you use jQuery then:
$.get('Order.php?itemdetails='+JSON.stringify(itemdata), function(response) {
});

Add enter for submit textarea

Hi i was created a new chat box,everithing is working but i need to when i click enter to sumit a message(to go to function Kucaj() ).Can you help me with that?
I add some code for enter but didnt work.Thanks
<?php
session_start();
if(!isset($_SESSION['username'])){
?>
<form name="forma2" action="login.php" method="post">
<table>
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" />
<tr>
<td colspan="2"><input type="submit" name"submit" value"Login"/td>
</tr>
<tr>
<td colspan="2">Registruj se!</td>
</tr>
<?php
exit;
}
?>
<html>
<head>
<title>Maturski rad</title>
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<script>
function Klikni(){
if(forma1.msg.value == ''){
alert('Upisi poruku!');
return;
}
var msg = forma1.msg.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
}
forma1.msg.value='';
}
xmlhttp.open('GET','insert.php?&msg='+msg,true);
xmlhttp.send();
}
$(document).ready(function(e) {
$.ajaxSetup({cache:false});
setInterval(function() {$('#chatlogs').load('logs.php');}, 2000);
});
</script>
</head>
<body>
<form name="forma1" action="#" id="forma1">
Username: <b><?php echo $_SESSION['username']; ?></b></br>
Poruka: <br />
<textarea name="msg" style="width:500px; height:100px"></textarea><br />
Posalji<br /><br />
Izloguj se<br /><br />
<script>
$("forma1").keypress(function(event) {
if (event.which == 13) {
event.Klikni();
}}
</script>
<div id="chatlogs">
Molim sacekajte da se ocita!!!
</div>
</body>
</html>
You can just add onsubmit=return Klikni(); attribute to your form and return false; to Klikni function without using .keypress(). Form submitted on user pressing enter is a default behaviour.
function Klikni(e) {
alert("Enter pressed");
return false;
}
<form name="forma1" action="#" id="forma1" onsubmit="return Klikni();">
Put your cursor into the field and press Enter.<br>
<input type="text">
</form>
try like this source,
form.submit(function(e) {
e.preventDefault();
$(this).find('[type=submit]').click();
$("form").submit();
})
Try keydown instead of keypress as:
$("forma1").keydown(function(event) {
You may use like this.It should be like this Klikni(); not like event.Klikni();
<script>
$("forma1").keypress(function(event) {
if (event.which == 13) {
Klikni(); //no need of event there..
}}
</script>

Categories