Validation for elements added on runtime - php

I am using the following script to add image input fields to my webpage. Everything is working fine, but what if I want to do the validation. I dont want to submit the form if any of the fields are empty. I tried the code i.e function validate() but it only checks for the first input field, i.e the input field of html. It doesnot work for the input fields added in runtime with the help of Jquery.
<script type="text/javascript">
function validate () {
var file = document.getElementById('file').value;
if(file==""){
alert("None of the Image Fields can be empty!!");
return false;
}
}
$(document).ready(function(){
$('#addproduct').click(function(){
$(this).after('<br /><input type="file" name="image_name[]" class="addfile" id="file" /> <input type="text" name="image_caption[]" placeholder="Caption for this image " size="60" /> ');
});
});
</script>
And I would like to add the delete functionality for the image fields. Like a cross button beside every input field, and the field be removed when clicked on that button.
<input type="file" name="image_name[]" id="file" required="true">
<input type="text" name="image_caption[]" placeholder="Caption for this image " size="60">
<span id="addproduct"></span>

Instead of document.getElementById('file') use document.getElementsByName('image_name[]') or jQuery style $('[name="image_name[]"]'). This is because the id of a tag must be unique, else only the first one can be referenced by id.
For the delete functionality use something like this:
$(document).ready(function(){
$('#addproduct').click(function(){
$(this).after('<br /><div><input type="file" name="image_name[]" class="addfile" id="file" /> <input type="text" name="image_caption[]" placeholder="Caption for this image " size="60" /> <input type="button" value="Delete" onclick="deleteRow(this)" /> </div>');
});
});
var deleteRow = function(elem) {
$(elem).parent().remove();
}

Related

Browsed file name is not getting displayed in textbox

<input title="Browse" type="file" name="file" onchange="this.parentNode.nextSibling.value = this.value.split('\\').pop().split('/').pop()">
Browse
From the above code i am uploading file and uploaded file is working fine but when i click upload button the current browsed file name is not getting displayed in the text box which i provided.
Since you'll display the file-name in a separate text-box and you won't use the default filename display. It's better to create a button and have it call the file-upload using onclick. After that you can get the file-name and assign it to the text-box you created using the javascript below.
javascript:
var filename;
document.getElementById('fileInput').onchange = function () {
filename = this.value.split(String.fromCharCode(92));
document.getElementById("fileText").value = filename[filename.length-1];
};
HTML:
<label for="file" class="input input-file">
<input type="text" id="fileText" placeholder="Upload Students file" readonly="" />
<input type="file" id="fileInput" style="display: none;" />
<input type="button" value="Choose File" onclick="document.getElementById('fileInput').click();" />
</label>
I've made a quick demo for you here: http://jsfiddle.net/x9L8etfg/
Hope this helps.
you have to parse to the parent of text node, then only you can set the value.
use this:
onchange="this.parentNode.parentNode.childNodes[1].value = this.value.split('\\').pop().split('/').pop()"

Remove the form input fields data after click on submit?

hi i am using a form for users subscription on the website with target is _new.
when i click on the submit button that the submitting message shows on the new window but the previous window still holding the data.
How to remove input fields data after submitting.
<form target="_new" action="samplepage.php" method="post">
<input type="text" name="inputtxt1" />
<input type="text" name="inputtxt2" />
<input type="submit" value="submit" />
</form>
Any suggestions???
Make the autocomplete - off
try this
<form target="_new" action="samplepage.php" method="post" autocomplete="off">
<input type="text" name="inputtxt1" />
<input type="text" name="inputtxt2" />
<input type="submit" value="submit" />
</form>
Reset form data using this
$('form').get(0).reset();
$(document).ready(function(){
$('form_name').submit(function(){
$('input[type="text"]').val('');
});
});
You can set value to null for text field using jquery on submit button click
$("input[type=submit]").click(function()
{
$("input[type=text]").val('');
});
EDIT:
I don't know is this a good approach, use blur instead of click event
$("input[type=submit]").blur(function()
{
$("input[type=text]").val('');
});
But it will meet your need.

Updating a variable in jQuery script

I am currently building a dynamic form, using a bit of HTML, PHP and jQuery. This form contains a drop down select field (with the tag name) and two input boxes named tag_text_color and tag_background_color.
When you select a tag in the select field, a bit of jQuery will fill the boxes tag_text_color and tag_background_color with the current database value.
Before that, I have a form which allow the user to add a tag in the database. My problem occurs when I right before adding a tag in the database.
Here is the code for adding a tag :
<form id="form_addtag" method="post" name="form_addtag" action="add_tag.php">
<legend>Add a tag</legend>
<input type="text" name="tag_name" id="tag_name" class="text" size="30" placeholder="Tag Name" />
<input type="text" name="tag_text_color" id="tag_text_color" class="text" size="6" placeholder="#ffffff"/>
<input type="text" name="tag_bg_color" id="tag_bg_color" class="text" size="6" placeholder="#000000" />
<button type="submit" id="button_save_tag">Add</button>
</form>
and the jQuery corresponding function :
$( document ).ready(function() {
$("#form_addtag").submit(function(e) {
e.preventDefault();
var url = "add_tag.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#form_addtag").serialize(), // serializes the form's elements.
});
$('#form_addtag')[0].reset();
$("#form_edittag").load("demo.php #form_edittag")
});
Adding a tag works fine, and it reloads perfectly the form to edit a tag. However if in this block I am selecting the new tag, it is not loaded yet by jQuery
HTML to edit a tag :
<form id="form_edittag" method="post" name="form_edittag" action="edit_tag.php">
<legend>Edit a tag</legend>
<select id="select_edittag">
<?php
$tags = get_tags();
$numberOfTags = sizeof($tags);
var_dump($numberOfTags);
var_dump($tags);
foreach ($tags as $line)
{
echo("<option value='".$line["name"]."''>".$line["name"]."</option>");
}
//print("<option value='". $tags[ $j ]["name"]."'>".$tags[ $j ]["name"]."</option>");
?>
</select>
<input type="text" name="tag_text_color_edit" id="tag_text_color_edit" class="text" size="6" />
<input type="text" name="tag_bg_color_edit" id="tag_bg_color_edit" class="text" size="6" />
<button type="submit" id="button_edit_tag">Edit</button>
<button type="submit" id="button_delete_tag">Delete</button>
</form>
Corresponding jQuery :
$( document ).ready(function() {
$( document ).on( "change", "select#select_edittag", function()
{
var name = $("#select_edittag").val();
var tags = <?php echo json_encode(get_tags()); ?>;
$("#tag_text_color_edit").val(tags[name]["text_color"]);
$("#tag_bg_color_edit").val(tags[name]["background_color"]);
});
});
The function get_tags() will return an array with all the tags in the database.
I was thinking that each time I select a new item in my select "select_edittag" it would run the script, and update the tags variable with the lastest content from the function get_tags(). It does not sadly.
Any idea ? If you want a live demo I can host something like that
No.
PHP is running once, when loading the page. You must repopulate 'tags' via ajax. Check: getJSON

jQuery form validation with dynamically generated forms

I have a page with several forms which are dynamically generated using PHP. I am validating them using the jQuery Validation plugin. The forms are all the same, but relate to different items so I have given all of the forms the same class so they can be validated by one function (each form also has a unique ID). But I'm having some problems:
I would like the error messages to appear by the correct form items, but if I'm just using the form's class, the validator won't know which form the item is from.
I have a hyperlink to submit the form (and a regular submit button in <noscript> tags), and would usually use jQuery to submit the form, but again, how will jQuery know which submit link I've clicked, and which form to submit?
The easiest thing I can think of is to pass the form ID to the validate some how. Is that possible?
The forms look like this:
<?php while($row= pg_fetch_row($groups)) { ?>
<p class="error" id="error-<?php echo $row[0] ?>"></p>
<form action="../scripts/php/groups-process.php" method="post" id="editgroup-<?php echo $row[0] ?>" class="editgroup">
<label for ="edit-<?php echo $row[0] ?>" >Edit group name:</label>
<input type="text" class="text" size="20" maxlength="30" name="edit" id="edit-<?php echo $row[0] ?>" value="<?php echo $row[1] ?>" />
<noscript><input type="submit" name="editgroup" value="Submit" /></noscript>
<div id="submitcontainer-<?php echo $row[0] ?>"></div>
</form>
<?php } ?>
I would normally validate the form like this:
$(document).ready(function(){
$("#editgroup").validate({
rules: {edit: {required: true, maxlength: 30}},
messages: {edit: {required: 'Please enter a group name', maxlength: 'Please enter a shorter group name'},
errorContainer: "p#error",
});
$("#submitcontainer").html('<a class="button" href="javascript:void();" id="submitlink" name="submit">Submit</a>');
$("#submitlink").click(function() {
$("#editgroup").submit();
});
});
give the same class to all the form than try this,
<form id="1" class="common" method="post" action="page.php">
<input type="text" class="common_input_class" size="20" maxlength="30" name="edit" id="whatever" value="whatever" />
<input type="submit" name="submit" class="submit_this_form" value="submit" />
</form>
<form id="2" class="common" method="post" action="page.php">
<input type="text" class="common_input_class" size="20" maxlength="30" name="edit" id="whatever" value="another value" />
<input type="submit" name="submit" class="submit_this_form" value="submit" />
</form>
<script type="text/javascript">
$(".common").submit(function(){
var form_id = $(this).attr('id');
var input_val = $(this).children('.common_input_class').val();
if (input_val == '')
{
alert("input field is required");
return false;
}
});
</script>
I ended up iterating through my result twice, so I create a form validator for each form dynamically, and then dynamically create the forms. This was the best way I could think of to give me the control I wanted, although obviously it's slower and produces more code - not an ideal solution but it will do for this situation.

Removing empty Input Elements from a form

I have a simple form that goes on to create all the form and validation requirements for codeigniter. What I want to do is filter out any empty inputs prior to serialization so that I do not create form inputs and form validation set rules. I am at a loss as to how to go about this. Where I have the alert in the Jquery is where I want to remove any empty inputs(again prior to serialization). At this point what I am using does not detect empty form fields. Without the detection code the entire system works fine. Here is what I am using
<h1>Field Name</h1>
<form action="Form.php" onsubmit="return false;" id="form" method="post">
<input type="text" name="v1" id="v1" />
<input type="text" name="v2" id="v2" />
<input type="text" name="v3" id="v3" />
<input type="text" name="v4" id="v4" />
<input type="text" name="v5" id="v5" />
<input type="text" name="v6" id="v6" />
<input type="submit" name="send" id="send" value="Send" />
</form>
<hr />
<script>
$(function(){
$('#send').click(function(){
---------------------------------------
$(":input").each(function() {
if($(this).val() === "")
alert("Empty Fields!!"); //using alert just to see if empty fields are detected.
return false;
});
-----------------------------------------
var data = $('#form').serialize();
$.ajax({
type: "POST",
data: data,
url: "Form.php",
success: function(msg){
if(msg){
$('#display').html(msg).show();
}else{
$('#display').text("<p>nothing came back</p>");
}
}
});
return false;
});
});
I am simply trying to avoid printing out empty form fields
<p>
<label for=""></label> <br />
<input type="text" name="" id="" /> <br />
<label class="error" id=""> This field is required</label> <br />
<p/>
Thank you for your time
This will remove all the text fields which have a value of length 0:
$('#send').click(function(){
$(':input[type="text"]').filter(function(e){
if (this.value.length===0){
return true;
}
}).remove();
});
example: http://jsfiddle.net/niklasvh/ZBSyX/
You should use a regex expression using \s as the search query. So /^(\s)*$/ as the regex and just make sure input does not match this.
Sorry but I am not familiar with Jquery or I would write the code out exactly.
$('#send').click(function(){
//---------------------------------------
$(":input").each(function() {
if($(this).val() === "")
alert("Empty Fields!!"); //using alert just to see if empty fields are detected.
return false;
});
And you're not getting an error from this? The first lambda's scope isn't closed.
Use Firebug to highlight errors that you might be getting and post those.
To hide elements that have no value assigned:
$('input:text[value=""]').hide();
But, of course, if a value="x" attribute is provided in the html this will result in the element being shown.

Categories