JQuery - Disable form unless value isn't NULL? - javascript

Not too familiar with JQuery, but I'm basically trying to do the same thing that asked here:
Inputs disabled until previous input filled in
.. And that question was answered successfully, with this being the most suitable answer: http://jsfiddle.net/WYhNm/ (The code I'm using as well)
...In my case, however, there's an exception: If the field already has a value, and if that value is not null, then it shouldn't be disabled. The reason for this is because I'm working with a PHP/HTML5 form that allows previewing before submission - So the field's value is passed through the form, and put back into the the field as it's value all on the same page.
Example:
//PHP
$tag1 = $_POST["Tag1"];
$tag2 = $_POST["Tag2"];
$tag3 = $_POST["Tag3"];
$output ='<form method="post" name="post_form"
action="process_post.php">
<input type="text" class="tag" name="Tag1" value="' . $tag1 . '">
<input type="text" class="tag" name="Tag2" value="' . $tag2 . '" disabled>
<input type="text" class="tag" name="Tag3" value="' . $tag3 . '" disabled>
<button type="submit" name="submit" value="publish_post">Publish Post</button>
<button type="submit" name="submit" value="preview_post">Preview Post</button>
</form>';
I've tried running comparisons in jQuery using my PHP knowledge - That didn't go so well as I have no idea what I'm really doing:
var next_step = $(this).next('.tag');
var input = $(this).val('.tag');
if ($(this).val()) {
next_step.attr('disabled', false);
}
elseif ( input == "" ) { //Is elseif even valid here?
next_step.attr('disabled', true);
}
tl;dr - Using this JSFiddle, how can I enable the "disabled" fields if their value = anything non-null?

I hope I understand your question correctly.
$('.step').change(function() {
var next_step = $(this).next('.step');
// If the element *has* a value
if ($(this).val()) {
next_step.attr('disabled', false);
}
// If the element doesn't have a value
else {
if(!next_step.val()) next_step.attr('disabled', true); // <--
}
});
Only disable if your element's value evaluates to false.
if(!next_step.val()) next_step.attr('disabled', true); // <--
Hope this helps!

Related

How to get value of hidden filed which is set in javascript

I have a hidden field. When user click on a button (here delete button) its value is set is as one in java script.Now I want to get its value on posting the input field - submit .
My code is here.
<input type="hidden" name="clicked_delete_btn" id="clicked_delete_btn" value=""/>
<input type="button" name='delete' id='delete' value="Delete" onClick="return confirm_delete(this);">
<input type="submit" name="update" value="UPDATE" >
javascript
function confirm_deleteo(ele) {
if (confirm('Do you wish to delete the file?')) {
ele.style.display = 'none';
document.getElementById('clicked_delete_btn').value = 1;
return true;
} else return false;
}
php code
if(isset($_POST['update'])) {
$delete_clicked=$_POST['clicked_delete_btn'];
if($delete_clicked==1) {
//do operations
}
}
But it's value is not getting on $_POST['update'].
You need to use ID instead of name
document.getElementById('clicked_photo_delete_btn').value = 1;
I have tried to assemble your code and it works fine on my system:
http://pastebin.com/NAEYAZre, http://pastebin.com/3vEsrHJJ
Check your form tag options.

Cancel a form to be submitted, do not change the data of the entity

I have a div
<div id="updateChoice%s" class="text-center"></div>
which shows a the following upon a "updateText" button is clicked
function updateText(urlsafe) {
document.getElementById("updateChoice"+urlsafe).innerHTML +=
'<br><br><form id="dynForm" action="/updateText" method="post" >' +
'<textarea name="newContent" rows="5" cols="80"></textarea>' +
'<input type="hidden" name="update" value=' + urlsafe + '>' + '<br><br>' +
'<input class="choice" type="submit" value="Submit"></input> <button class="choice" onclick="cancelUpdate('+ urlsafe +')">Cancel</button>' +
'</form>';
}
I want to cancel the updating of the text but it doesn't work unless "newContent" is empty, here is /updateText file and cancelUpdate(urlsafe)
/updateText:
class UpdateText(webapp2.RequestHandler):
def post(self):
greeting_key = ndb.Key(urlsafe=self.request.get('update'))
event = greeting_key.get();
if(self.request.get('newContent') != ''):
event.content = self.request.get('newContent');
event.put();
self.redirect('/events');
cancelUpdate(urlsafe):
function cancelUpdate(urlsafe) {
document.getElementByName("newContent").innerHTML="";
document.getElementById("dynForm").submit();
}
any ideas?
The /updateText handler remains on not updating the text if upon submission it is empty, so do not change anything:
In the cancelUpdate(urlsafe) function, use this aproach:
function cancelUpdate(urlsafe) {
document.getElementById("updateChoice"+urlsafe).innerHTML = "";
}
Add \' to the parameter urlsafe as you pass it and not ". So here is correct javascript function call to div#updateChoice%s is:
function updateText(urlsafe) {
document.getElementById("updateChoice"+urlsafe).innerHTML =
'<br><br><form id="dynForm" action="/updateText" method="post" >' +
'<textarea name="newContent" rows="5" cols="80"></textarea>' +
'<input type="hidden" name="update" value=' + urlsafe + '>' + '<br><br>' +
'<input class="choice" type="submit" value="Submit"></input><button type="button" class="choice" onClick="cancelUpdate(\''+ urlsafe +'\')">Cancel</button>' +
'</form>';
}
Your question is very difficult to understand (What do you mean by "cancel the updating of the text"? What did you expect to happen? What exactly "doesn't work"?).
Also, there are multiple issues with the code you provided (none of which have to do anything with GAE, Python or webapp2), here are a few that might be helpful to resolve your issue:
1) Your cancelUpdate function accepts a urlsafe parameter but is not using it.
2) In your cancelUpdate function you're using a non-existing function getElementByName, you probably meant to use its plural version getElementsByName()
3)
On the same document.getElementByName("newContent").innerHTML=""; line you are retreiving an element with the name newContent which is a <textarea> element and are attempting to empty its innerHTML property, but a <textarea> doesn't have one. If you want to empty a <textarea>'s contents - you need to do document.getElementByName("newContent").value=""; instead.
Since your cancelUpdate function has an unused parameter urlsafe and although it's not clear what your issue is but since in your updateText function you are creating an element with id="updateChoice"+urlsafe and assuming that when you hit cancel - you also want to destroy that form, then your cancelUpdate would look as simple as this:
function cancelUpdate(urlsafe) {
document.getElementById("updateChoice"+urlsafe).innerHTML = "";
}
4)
Your "Cancel" button doesn't have a type specified which means it will default to submit even when you don't want to submit the form so you need to add type="button" to prevent the submission.
You are calling document.getElementById("dynForm").submit(); in your cancelUpdate function which in the combination with the previous issue will submit your form twice.

php form to javascript

I need to pass the form id to javascript, but always shows the same data.
<script>
$(document).ready(function() {
$('input[name="submit"]').on('click', function(){
var vauid = $( "input[name='uid']" ).val(); alert("\n ID: "+vauid);
return false;
});
});
</script>
<? include "../includes/config.php";
$sql = "select * from table";
$reg = mysql_query($sql);
while($row = mysql_fetch_array($reg)){ ?>
<form action="" method="POST">
<input type="text" name="uid" value="<? echo $row['uid']?>" />
<input type="submit" name="submit" value="Show"/>
</form>
<? }?>
Part of the problem is that you're inserting numerous forms with elements having the same names - that is a bad idea as names are intended to be unique.
Second, when you click you have to reference the currently clicked info:
$(document).ready(function() {
$('input[name="submit"]').on('click', function(e){
e.preventDefault();
var vauid = $(this).prev("input[name='uid']").val();
console.log("ID: "+vauid);
});
});
Here is a working demo.
$(this) will be the clicked button from which we look for the previous input's value. I'm also using preventDefault() to stop the button's default action, rather than returning false.
In addition you should quit using alert() for troubleshooting., use console.log() instead.

Html5 required validation checkbox

I made a input checkbox that contains array values. so it generates plenty of rows in a table.
But it needs for me to check it all to submit.
It doesn't allow me to check only few not all.
<form>
<table>
<td>
<input required="required" type="checkbox" name="id[]" id="id" value="<?php echo $result2["id"]; ?>"/>
</td>
<input type="submit" name="submit" value="submit"/>
</table>
</form>
How can i make the required field able to check atleast one and able to submit even if not all are checked?
I dont know if I understand you,
but maybee you need something like this:
Online demo
Main part with notes:
$('#frm').bind('submit', function(e) { // set this function for submit for your formular
validForm = true; // default value is that form is correct, you can chcange it as you wish
var n = $( "input:checked" ).length; // count of checked inputs detected by jQuery
if (n != 1) { validForm=false; } // only if you checked 1 checkbox, form is evaluated as valid
if (!validForm) { // if result of validation is: invalid
e.preventDefault(); // stop processing form and disable submitting
}
else {
$('#echo').html("OK, submited"); // ok, submit form
}
});
You can use any number of comboboxes under any tag and get count of selected by jQuery, then use any rule for validate form.

Check if fields are edited or not? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have 7 textfields put inside a table. These textfields data i get from server when user presses submit. After filling textfield with fetched data, user submits that data to the server from a new button submit.
If the user submits the data as it is, I need to show an error message that 'at least one field must be edited'. If it edits at least one field and then submits I will update data on the server.
How can I check whether user has changed a field or not?
Problem is I will need to store data fetched for comparison, which I will have to do it in global variable in my JavaScript (which is not a good practice).
You can create an hidden input (like say #lastr2d2) named haschange like
<input type="hidden" name="haschange" id="haschange" value="0" />
and add an jquery or javascript function witch change the value of haschange from 0 to 1
when happens an event onChange on each textfields. for example you can create a function like bellow:
$(document).ready(function(){
//Check this link
$("#textfields1").change(function(){
$("#haschange").val(1);
});
});
Finally when you click the button of finally submit then you can check if haschange value is 0 or 1
--- Edit ---
If you want check for original changing (see #antindexer comments) then you can use below code
$(document).ready(function(){
//Check this link
$("#textfields1").change(function(){
var defaultValue = document.getElementById('textfields1').defaultValue;
var currentValue = document.getElementById('textfields1').value;
if( currentValue != currentValue ) {
$("#haschange").val(1);
}
});
});
You could do something like this:
Add data attributes to your input fields. Replace "<%= serverValue %>" with whatever syntax your server code uses.
<form id="form">
<table>
<tr>
<td><input type="text" value="<%= serverValue %>" data-original-value="<%= serverValue %>" /></td>
</tr>
</table>
<input type="submit" value="submit" />
</form>
And then place a script tag on the page with something like this (assuming you're using jQuery):
<script>
$(function () {
var $form = $('#form');
$form.on('submit', function (e) {
$(form).find('[data-original-value]').each(function (index, el) {
var $el = $(el);
if ($el.val() === $el.attr('data-original-value]')) {
e.preventDefault();
console.log('please edit at least one value');
}
});
});
});
</script>
Here is a JSFiddle - http://jsfiddle.net/X4S4y/1/
You can use attr data-value ( or any name you want ) to keep your original value
Example: ( Assume you use PHP )
<input type="text" value="<?php echo $value_1?>" data-value="<?php echo $value_1?>" class="input_text">
<input type="text" value="<?php echo $value_2?>" data-value="<?php echo $value_2?>" class="input_text">
<input type="text" value="<?php echo $value_3?>" data-value="<?php echo $value_3?>" class="input_text">
<input type="text" value="<?php echo $value_4?>" data-value="<?php echo $value_4?>" class="input_text">
In Jquery you can check if there are any change in input text then submit form
Example:
$(document).ready(function(){
$("form").submit(function(){
var is_changed = false;
$(".input_text").each(function(){
if ( $(this).val() == $(this).attr("data-value") {
return false;
} else {
is_changed = true;
}
});
if( is_change == true ) {
alert("Please change at least one input");
return false;
}
});
})

Categories