JavaScript challenging form elements array validation - javascript

I have one HTML form:
<form name="modeladd" ethod="post" class="form label-inline" enctype="multipart/form-data" onSubmit="return check('modeladd');">
<?php for($i=0;$i<$tot;$i++) { ?>
<div class="field">
<label for="connect_msg">Connect Message </label>
<textarea rows="4" cols="50" name="connect_msg[<?php echo getField($langs[$lan]);?>]" id="connect_msg[]"><?php echo getField($row[$lan]); ?></textarea>
</div>
<div class="field">
<label for="call_msg">Call Message :</label>
<textarea rows="4" cols="50" name="call_msg[<?php echo getField($langs[$lan]);?>]" id="call_msg"><?php echo getField($row[$lan]); ?></textarea>
</div>
<div class="field">
<label for="stripline_msg">Stripline Message :</label>
<textarea rows="4" cols="50" name="stripline_msg[<?php echo getField($langs[$lan]);?>]" id="stripline_msg"><?php echo getField($row[$lan]); ?></textarea>
</div>
<div class="field">
<label for="cost_msg">Cost Message :</label>
<textarea rows="4" cols="50" name="cost_msg[<?php echo getField($langs[$lan])?>]" id="cost_msg"><?php echo getField($row[$lan]); ?></textarea>
</div>
<?php } ?>
<input type="submit" class="btn btn-grey" value="submit">
</form>
Here is the JavaScript for validation:
function check(form)
{
var name = new Array();
name =document.getElementById('connect_msg[]').value;
for(var i=0 ; i<=1; i++)
{
alert(name[i].value);
}
return true;
}
I am not getting value for both the connect_msg field which is array. I want to validate both the field value using JavaScript so please help me.

The id cannot have [] symbols. Please validate your markup: http://validator.w3.org/
The value returned from an element is type string, so you can't get an array. What you can do is parse the string to create your array.
Eg. Assuming the following is the outputted markup:
<textarea id="connect_msg">a,b,c,d,e,f,g</textarea>
You can do this in JavaScript:
var getConnectMsg = document.getElementById('connect_msg').value;
var connectMsgArray = getConnectMsg.split(',');
And connectMsgArray will contain ['a','b','c','d','e','f','g'].
You can read more about .split() here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/split
Edit: Since you say the textarea is in a loop, then it's more easier to retrieve the elements using class name attribute, and using jQuery will help you immensely.
So the HTML output would be like this:
<textarea class="connect_msg" id="connect_msg1">a,b,c,d,e,f,g</textarea>
<textarea class="connect_msg" id="connect_msg2">h,i,j,k,l,m,n</textarea>
<textarea class="connect_msg" id="connect_msg3">q,r,s,t,u,v</textarea>
var getConnectMsg = $('.connect_msg');
getConnectMsg.each(function(){
var getValue = $(this).val();
var connectMsgArray = getValue.split(',');
});
In each iteration of the .each(), the value of getValue would be:
a,b,c,d,e,f,g
h,i,j,k,l,m,n
q,r,s,t,u,v
You can do your form validation for a set of fields during each iteration.

the name can't be a multi-dimensional array change this:
name="connect_msg[<?php echo getField($langs[$lan]);?>]"
To this:
name="connect_msg[]"
And then address them in the post script with a foreach loop.
And about the id use this instead() I don't know if it's true that you can't use [] in the id but I know this worked for me:
id="connect_msg_<?php echo getField($langs[$lan]);?>"
Update:
I think your right, maybe using a class instead of id is the way to go.
class="connect_msg"
And then in the form check function instead of this:
var name = new Array();
name =document.getElementById('connect_msg[]').value;
Do this:
var connectMsg = document.getElementByClassName('connect_msg');
And then loop through the connectMsg array and get/validate the values.
Hope this help.

Related

Password field from MySql to PHP

I'm trying to hide a password field from a MySql DB to my web app, but i just can't, I'm using a label to show the password field from the DB like this:
<div class="control-group">
<label class="control-label">Password</label>
<div class="controls">
<label class="checkbox">
<?php echo $data['password'];?>
</label>
</div>
</div>
But i want to hide the password, and i can't find any way to to it..
<input id="pw" type="password" value="<?php echo $data['password']; ?>">
Then you can use a button and JS to change type="password" to type="text"
var pw = document.querySelector('#pw'); // input
var seePw = document.querySelector('#see-pw'); // button
seePw.addEventListener('mousedown', function(){
pw.setAttribute('type', 'text');
});
seePw.addEventListener('mouseup', function(){
pw.setAttribute('type', 'password');
});
<?php //echo $data['password'];?>
may help you
PS nothing to do with java
Never retrieve password from your database also present it. Your risky design should be replaced by a password field which sample data.
May one of the following is the solution for you.
You can add the class hidden to the element.
Use HTML form field as:
< input type="password" value="echo $data['password'];" disabled>

prevent result, show through AJAX, after reload browser

I have a insert query through ajax. It is working correctly. But when I reload browser then result disappears from div section and if I insert form through ajax again then result is showing.
I have a file first.php (in which, form is present), a AJAX code and a firstcall.php where query will be execute.
My first.php (html form) is:
<form class="reservation-form mb-0" action="" method="post" autocomplete="off">
<input name="name1" id="name1" class="form-control" type="text" placeholder="Enter Name" required aria-required="true">
<input name="age" id="age" class="form-control" required type="number" placeholder="Enter Age" aria-required="true">
<input type="checkbox" id="checkbox" class="checkbox1" name="namec[]" value="<?php echo $value['id']; ?>" >
<input type="button" class="pull-right btn btn-warning" value="Submit" id="submit">
</form>
Here data should be display:
<div class="col-md-5">
<div class="panel panel-primary" id="showdata">
<!-- Here is the results, but when reload browser then result disapper-->
</div>
</div>
AJAX is:
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var name1 = $("#name1").val();
var age = $("#age").val();
var chkArray=[];
$('.checkbox1:checked').each( function() {
chkArray.push($(this).val());
} );
var selected;
selected = chkArray.join(',') ;
if(selected.length > 1){
$.ajax( {
url:'firstcall.php',
type:'POST',
data:{name1: name1,age: age,namec: chkArray},
}).done(function(data){
$("#showdata").html(data);
});
}
else{
alert("Please at least one of the checkbox");
}
});
});
</script>
firstcall.php is:
<div class="panel panel-primary" id="showdata">
<?php
foreach($_POST['namec'] as $selected){
echo $selected;
$_SESSION['name1']=$_POST["name1"];
$_SESSION['age']=$_POST["age"];
echo $name1=$_SESSION['name1'];
echo $age=$_SESSION['age'];
$query=mysql_query("insert into patient_details (p_name,p_age,g_number) values ('$name1','$age','$selected')") or die(mysql_error());
}
?>
First of all fix your query to use MySQLi, instead of MySQL, check this or the PHP manual
Also don't ever add direct $_POST or $_GET variables into your mysql query, filter them first using mysqli_real_escape.
$name1 = mysqli_real_escape($link, $_POST["name1"]);
$age = mysqli_real_escape($link, $_POST["age"]);
After that, to show the data when the page reloads, you need to load the data with the page, easiest way to do that is just add in your HTML PHP tags with an echo command inside, adding your variables.
If I understand your question correctly, you want the Ajax result to also show on page load?
Right now you only execute the JS after a click (so on page load/relaod you will just see the html), you might want to execute it after page load aswell (so execute the script without the .click)
You could create a function once, and call it when the page is ready and on click.

My ajax code don't send the data to the database

I want to use ajax to add data in the database but nothing happens
i don't know whats wrong is it in the ajax!or in the php
This is part of my code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
$("#commentForm").submit(function(){
var U_N = $('input[name="U_N"]').val();
var I_name = $('input[name="I_name"]').val();
var context = $("#inputmessage").val();
$.ajax({
type: "POST",
cache: false,
url : "aAddComm_Menu.php",
data : {U_N:U_N,I_name:I_name,context:context},
});
});
});//end of document ready function
</script>
this the html form:
<form class="form-horizontal" role="form" id="commentForm" method="POST" action="">
<div class="form-group">
<label for="inputmessage" class="col-sm-2 control-label">comment</label>
<div class="col-sm-10">
<textarea name = "context" class="form-control" id="inputmessage" rows="3" placeholder="Enter your comment here . . "></textarea>
</div>
</div> <!-- End of /.form-group -->
<input type="hidden" value = "$Item['Item_Name']" name="I_name"/>
<input type="hidden" value ="$U_N" name="U_N"/>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button name="SendC" type="submit" class="btn btn-primary" ;>Send</button>
</div>
</div>
</form>
and this is a part of the php page for adding to the database
extract($_POST)
if(isset($context))
{
mysql_query("INSERT INTO menu_commnet VALUES('$I_name','$U_N',NULL,NOW(),'$context')");
}
var U_N = $("input#U_N").val();
var I_name = $("#I_name").val();
var context = $("#context").val();
The jQuery selectors are wrong, you're not selecting anything. The # selector stands for id attribute, but you're trying to select by value of name attribute. You should either add/change id attributes of your input fields, or use
var U_N = $("input[name=U_N]").val();
var I_name = $("input[name=I_name]").val();
var context = $("[name=context]").val();
Tip: next time use developer console inside your browser, you can easily test if selectors are correct. You can type in javascript code as you would inside .js file and test if it's working like you expect.
Also, don't do this in your PHP, use prepared statements.
Did you included you Database conection on your Backend script?
extract($_POST)
'if(isset($context)) {
mysql_query("INSERT INTO menu_commnet VALUES('$I_name','$U_N',NULL,NOW(),'$context')");
}'
i think here you should include you database info, 'include_once("database info.php"); , also make sure you ajax will return a result, and echo php errors, just to be sure its an ajax or php error,
I have few comment regarding your issue :
Replace $("document").ready(function(){ with
$(document).ready(function(){
Before extracting in PHP ,
try var_dump($_POST)
Based on your HTML code use:
var U_N = $('input[name="U_N"]').val();
var I_name = $('input[name="I_name"]').val();
var context = $("#inputmessage").val();
Here is final working example. Just add "ev" argument to submit callback function , then use ev.preventDefault() in it.
$(document).ready(function(){
$("#commentForm").submit(function(ev){
ev.preventDefault();
var U_N = $('input[name="U_N"]').val();
var I_name = $('input[name="I_name"]').val();
var context = $("#inputmessage").val();
$.ajax({
type: "POST",
cache: false,
url : "aAddComm_Menu.php",
data : {U_N:U_N,I_name:I_name,context:context}
});
});
});//end of document ready function
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form class="form-horizontal" role="form" id="commentForm" method="POST" action="">
<div class="form-group">
<label for="inputmessage" class="col-sm-2 control-label">comment</label>
<div class="col-sm-10">
<textarea name="context" class="form-control" id="inputmessage" rows="3"
placeholder="Enter your comment here . . "></textarea>
</div>
</div>
<input type="text" value="" name="I_name"/>
<input type="text" value="" name="U_N"/>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button name="SendC" type="submit" class="btn btn-primary">Send</button>
</div>
</div>
</form>

Make NicEdit appear in all instances given the same ID

I am trying to get NicEdit to work only for all textareas with IDs of 'r_desc'. Currently this occurs only for the first instance of a form that is generated within a while loop, and not the others. What am I doing wrong?
JavaScript
<script src="http://js.nicedit.com/nicEdit-latest.js" type="text/javascript"></script>
<script type="text/javascript">
bkLib.onDomLoaded(function() {
nicEditors.editors.push(
new nicEditor().panelInstance(
document.getElementById('r_desc')
)
);
});
</script>
PHP/HTML
$i=0;
while($i<5){ ?>
<form id="content" name="content" method="POST" action="index.php">
<textarea name="r_type" id="textarea"></textarea>
<textarea name="r_desc" id="r_desc"></textarea>
<textarea name="r_rate" id="textarea"></textarea>
<input type="submit" id="button" value="Update" />
</form>
<? $i++;
}
I have also tried:
bkLib.onDomLoaded(function () {
var textareas = document.getElementsByID("r_desc");
for(var i=0;i<textareas.length;i++)
{
var myNicEditor = new nicEditor();
myNicEditor.panelInstance(textareas[i]);
}
});
Elements are supposed to have unique IDs. The implementation of getElementById knows this and will only return the first element that matches the given ID.
You need to use a different approach of identifying elements that you want converted to Nicedit
If you use something like getElementsByClassName or getElementsByTagName instead (note that these return elementS not just an element)
PHP:
$i=0;
while($i<5){ ?>
<form id="content" name="content" method="POST" action="index.php">
<textarea name="r_type" class="to-nice"></textarea>
<textarea name="r_desc" ></textarea>
<textarea name="r_rate" class="to-nice"></textarea>
<input type="submit" id="button" value="Update" />
</form>
<? $i++;
}
JavaScript:
var els = document.getElementsByClassName("to-nice");

Javascript change value of attribute of firstChild

The problem:
I'm duplicating div's using a button.
Within the div's are parts of a form:
<form method="post" action="order-opstellen.php">
<div id="duplicate">
<input type="hidden" id="counter" value="0">
</div>
<input type="button" onclick="duplicate()" value="Add">
<button type="submit">Send</button>
</form>
I'm using this script:
<script type="text/javascript">
var i = 0;
var original = document.getElementById('duplicate');
function duplicate() {
var clone = original.cloneNode(true);
clone.id = "duplicate" + ++i;
clone.style.clear = "both";
original.parentNode.appendChild(clone);
var tempId = document.getElementById("duplicate" + i);
tempId.childNodes[0].value=i;
}
</script>
As you can see, I'm trying to change the value of each input.
Adding it with 1 every time I duplicate the div.
Obviously it is not working. How do I do this?
Update:
So I've got this first part working.
Now I need to go deeper.
<form method="post" action="order-opstellen.php">
<div id="duplicate">
<input type="hidden" id="counter" value="0">
<div class="form-group dispWidth fl">
<label>Productnaam</label>
<select class="form-control dispWidth" name="productnaam"> <?php
$sql_products = "SELECT * FROM product ORDER BY naam";
$results = $conn->query($sql_products)->fetchAll(PDO::FETCH_OBJ);
foreach ($results as $row) {
?>
<option value="<?= $row->productnr ?>"><?= $row->naam ?></option>
<?php }
?>
</select>
</div>
<div class="form-group dispWidth fl ml">
<label>Aantal</label>
<input type="text" name=amountCount class="form-control dispWidth" placeholder="Hoeveelheid">
</div>
</form>
What I want is every time I duplicate the div, the select-name has to be unique. Also the name of the last input has to be unique (amountCount).
Probably by con-catting the i variable behind them both (productnaam1, productnaam2, amountCount1.). How?!
childNodes[0] is the text node that contains the newline and indentation.
Try children[0] instead.
Also, tempId refers to the exact same thing as clone, so just use clone.children[0].value = i;

Categories

Resources