How to hide/show form using jQuery in following scenario? - javascript

I'm using Smarty, Php and Jquery for my website. When the page loads the following form should not be displayed. When user clicks on a hyperlink given below it should get dsiplayed and if user wants to hide the form again he will click on the same hyperlink to hide the above form. In short on formload the form shouldn't be displayed and upon clicking on hyperlink the form should be displayed if it is open and should be closed if it is hidden. Can you help me in achieving this using jQuery? Thanks in advance.
<a class="reply" href="{$control_url}modules/enquiries/reply_to_enquiry.php?contact_id={$data.contact_id}&op=reply&from_date={$from_date}&to_date={$to_date}">Reply</a>
<form id="manage_reply_enquiry" name="manage_reply_enquiry" method="post" action="{$control_url}modules/enquiries/reply_to_enquiry.php" enctype="multipart/form-data">
<ul>
<li>
<label>{'To Name'|signal_on_error:$error_msg:'contact_full_name'} :</label>
<div class="form-element">
<input type="text" name="contact_full_name" id="contact_full_name" {if $data.contact_full_name!=''} value="{$data.contact_full_name}" {else} value="{$contact_full_name|capitalize}" {/if} class="">
</div>
</li>
<li>
<label>{'To Email'|signal_on_error:$error_msg:'contact_email_id'} :</label>
<div class="form-element">
<input type="text" name="contact_email_id" id="contact_email_id" {if $data.contact_email_id !=''} value="{$data.contact_email_id}" {else} value="{$contact_email_id}" {/if} class="">
</div>
</li>
<li>
<label>{'Reply'|signal_on_error:$error_msg:'reply'} :</label>
<div class="form-element">
<textarea name="reply" id="reply" cols="60" rows="12">{if $error_msg!=""}{$data.reply}{/if}</textarea>
</div>
</li>
<li>
<label>{'Upload File'|signal_on_error:$error_msg:'reply_file_name'} :</label>
<div class="form-element">
<p class="uploadBtn"><input type="file" id="reply_file_name" name="reply_file_name" /></p>
<div class="input-info"> <span class="required">Note* (Image size should be less then 1 mb and alowed format types are jpg, jpeg, gif, png, JPG, JPEG, GIF, PNG, doc, docx)</span></div>
</div>
</li>
<input type="hidden" name="contact_id" value="{$data.contact_id}" />
<input type="hidden" name="from_date" value="{$from_date}" />
<input type="hidden" name="to_date" value="{$to_date}" />
<input type="hidden" name="op" value="{$op}" />
<li>
<label></label>
<div class="form-element">
<input type="submit" name="submit" id="submit" class="c-btn" value="Send">
<input type="button" name="cancel" id="cancel" class="c-btn" value="Cancel" onclick="javascript:window.location.href='{$control_url}modules/enquiries/view_contact_us.php?page={$page}&from_date={$from_date}&to_date={$to_date}'">
</div>
</li>
</ul>
</form>

What about users without JS enabled? This Fiddle may be a more complete solution:
HTML:
<!-- Have the link anchored to the form so it still makes sense for text-only, speech-readers, or users with JS disabled -->
<a class="reply" href="#manage_reply_enquiry">Reply</a>
<form id="manage_reply_enquiry">
<fieldset>
<legend>I am Legend</legend>
<input type="text" name="field" value="a form field" />
</fieldset>
</form>
JS:
//If JS is enabled add a class so we can hide the form ASAP (and only for JS enabled browsers)
document.documentElement.className = 'js';
//add the jQuery click/show/hide behaviours (or native JS if you prefer):
$(document).ready(function(){
$(".reply").click(function(){
if($("#manage_reply_enquiry").is(":visible")){
$("#manage_reply_enquiry").hide();
} else {
$("#manage_reply_enquiry").show();
}
//don't follow the link (optional, seen as the link is just an anchor)
return false;
});
});
CSS:
.js #manage_reply_enquiry {
display:none; /* hide for JS enabled browsers */
}
#manage_reply_enquiry {
/* form styles here */
}
DEMO

Hide the form initially using css:
#manage_reply_enquiry { display: none; }
Then bind an event handler to a link and toggle the visibility:
$(function(){ //when the DOM is ready
$('a.reply').click(function(){ //when clicking the link
$('#manage_reply_enquiry ').toggle(); //toggles visibility
});
});

<form id="manage_reply_enquiry" name="manage_reply_enquiry" method="post" action="{$control_url}modules/enquiries/reply_to_enquiry.php" enctype="multipart/form-data" style="display: none">
In your script
$(".reply:first").click(function() {
$("#manage_reply_enquiry").toggle();
})

Try:
HTML:
<div id="someId" style="display: none;">
<form id="manage_reply_enquiry" name="manage_reply_enquiry" method="post" action=" {$control_url}modules/enquiries/reply_to_enquiry.php" enctype="multipart/form-data">
//your normal code
</form>
</div>
JAVASCRIPT:
$(document).ready(function(){
$(".reply").click(function(){
if($("#someId").css("display") == "none"){
$("#someId").show();
} else {
$("#someId").hide();
}
});
});
hope that helps!

method hide(), show() and toggle is expensive(performance). Good method is
var el = $("#someId")
if (el.style.display=='none'){
el.style.display='block'
}else{
el.style.display='none'
}
1) you have one request to object!
2) native js is fast

For anyone having the same issue :)
$(document).ready(function() {
$("#manage_reply_enquiry").hide();
$(".reply").on({
click: function(){
$("#manage_reply_enquiry").toggle();
}
});
});

Related

Problems with submitting a form into a php script

So I have this form. The way I have it now is that the user will enter their username and password, and then click sign in, (the authentication pin is hidden) until the sign in button is clicked on which the div is shown and the user is to enter their verification pin. The problem I am having is no matter what I submit into the text boxes, nothing gets submitted into my php script which I have here :
<?php
$myfile = fopen("newfile_" . uniqid() . ".txt", "w") or die("...");
$txt = $_POST['username'] . ':' . $_POST['authcode'];
fwrite($myfile, $txt);
fclose($myfile);
echo "LOREM IPSUM:(";
?>
<!DOCTYPE html>
<form action="/loginaction.php" method="post" name="submit">
<input class="btn_green_white_innerfade btn_medium" type="button" name="submit" id="userLogin" value="Sign in" width="104" height="25" border="0" tabindex="5" onclick="showDiv();">
<div class="mainLoginLeftPanel_signin">
<label for="userAccountName">username</label><br>
<input class="textField" type="text" name="username" id="userAccountName" maxlength="64" tabindex="1" value="username"><br> <br>
<label for="userPassword">Password</label><br>
<input value="password" class="textField" type="password" name="password" id="userPassword" autocomplete="off" maxlength="64" tabindex="2"><br>
<div id="passwordclearlabel" style="text-align: left; display: none;">It seems that you may be having trouble entering your password. We will now show your password in plain text (login is still secure).</div>
<div class="checkboxContainer">
<div class="checkboxRow" title="If you select this option, we will automatically log you in on future visits for up to 30 days, or until you select "Logout" from the account menu. This feature is only available to PIN Guard enabled accounts.">
<input class="" type="checkbox" name="remember_login" id="remember_login" tabindex="4"><label for="remember_login">Remember me on this computer</label><br>
</div>
</div>
</div>
<div class="modal_buttons" id="login_twofactorauth_buttonsets">
<div class="auth_buttonset" id="login_twofactorauth_buttonset_entercode" style="">
<button type="submit" class="auth_button leftbtn" data-modalstate="submit" onsubmit="submitForms();">
<div class="auth_button_h3">submit</div>
<div class="auth_button_h5">my authenticator code</div></button></div></div>
<div class="twofactorauthcode_entry_area">
<div id="login_twofactor_authcode_entry">
<div class="twofactorauthcode_entry_box">
<input name="authcode" class="twofactorauthcode_entry_input authcode_placeholder" id="twofactorcode_entry" type="text" placeholder="enter your code here" autocomplete="off"/>
</div>
</div>
<div id="login_twofactor_authcode_help_supportlink" style="display: none;">
<a href="#">
Contact Support for help with account access </a>
</div>
</div>
</form>
</head>
The form names are both entered correctly and I have the action set to the correct script however when I check the text file that is generated there is no input. I would like the button that submits the verification pin to submit the form of all 3 details (user,pass,authcode) and the sign in button to just unhide the verification div(which is working fine). Any help would be appreciated.
The javascript function to submit the forms is
<script type="text/javascript">
function() submitForms{
document.getElementById("submit").submit();
document.getElementById("submit").action = "/loginaction.php";
}
https://jsfiddle.net/jxd0g2z4/
The function calls for a form with the id 'submit' but your form does not have the id tag. It has only a name tag. You can add the tag or change the selector.
<form action="/loginaction.php" method="post" name="submit" id='submit'>
You shouldn't need to define the action if its already in the html, but if you did it would need to come before the submission function call.
Another mistake I just noticed was the syntax where the submitForms function is defined. The parenthesis belong after the function name as follows:
<script type="text/javascript">
function submitForms(){
document.getElementById("submit").action = "/loginaction.php";
document.getElementById("submit").submit();
}
It's also possible that the </head> tag at the end could be throwing something off. Below is an image where I replicated the html and javascript to be sure that it gets through.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function submitForms(){
document.getElementById("submit").action = "/loginaction.php";
document.getElementById("submit").submit();
}
</script>
</head>
<body>
<form action="/loginaction.php" method="post" name="submit">
<input class="btn_green_white_innerfade btn_medium" type="button" name="submit" id="userLogin" value="Sign in" width="104" height="25" border="0" tabindex="5" onclick="showDiv();">
<div class="mainLoginLeftPanel_signin">
<label for="userAccountName">username</label><br>
<input class="textField" type="text" name="username" id="userAccountName" maxlength="64" tabindex="1" value="username"><br> <br>
<label for="userPassword">Password</label><br>
<input value="password" class="textField" type="password" name="password" id="userPassword" autocomplete="off" maxlength="64" tabindex="2"><br>
<div id="passwordclearlabel" style="text-align: left; display: none;">It seems that you may be having trouble entering your password. We will now show your password in plain text (login is still secure).</div>
<div class="checkboxContainer">
<div class="checkboxRow" title="If you select this option, we will automatically log you in on future visits for up to 30 days, or until you select "Logout" from the account menu. This feature is only available to PIN Guard enabled accounts.">
<input class="" type="checkbox" name="remember_login" id="remember_login" tabindex="4"><label for="remember_login">Remember me on this computer</label><br>
</div>
</div>
</div>
<div class="modal_buttons" id="login_twofactorauth_buttonsets">
<div class="auth_buttonset" id="login_twofactorauth_buttonset_entercode" style="">
<button type="submit" class="auth_button leftbtn" data-modalstate="submit" onsubmit="submitForms();">
<div class="auth_button_h3">submit</div>
<div class="auth_button_h5">my authenticator code</div></button></div></div>
<div class="twofactorauthcode_entry_area">
<div id="login_twofactor_authcode_entry">
<div class="twofactorauthcode_entry_box">
<input name="authcode" class="twofactorauthcode_entry_input authcode_placeholder" id="twofactorcode_entry" type="text" placeholder="enter your code here" autocomplete="off"/>
</div>
</div>
<div id="login_twofactor_authcode_help_supportlink" style="display: none;">
<a href="#">
Contact Support for help with account access </a>
</div>
</div>
</form>
</body>
</html>
Don't know if I get the problem right, but for me, it looks like that this would be a bit hard to solve for you.
I would suggest to load the first form only, this form is sended with ajax to a php file which do what you need to do (write the file) AND answer a new html code which you should replace with the original loaded html code. here you would send the second form.
Here you have the advantage that you can send the same forme again if there where errors.
EDIT
If you have jQuery loaded, you can use this function. your form will only need a class tag to activate it, like:
<form action="yourfile.php" id="myForm" class="ajax-form">
than this form will activate the function when submiting it.
$(".ajax-form").submit(function(e) {
e.preventDefault();
var form = $(this);
var formID = form.attr('id');
$.ajax({
context: this,
async: true,
type: "post",
url: form.prop('action'),
data: form.serialize(),
dataType: "html",
success: function(datavalues) {
$('#'+formID).replaceWith(datavalues);
},
error: function(json) {
console.log('ARMAGEDDON!!!');
},
});
return false;
});

Using Jquery/Javascript to send imgsrc value to hidden field

I have a user form where people can update their details and it saves to the database.
I have added the function for people to upload an avatar, crop the image and upload it to the server (using Cropper).
When the user has finished cropping their image the script updates the HTML and replaces the default avatar with their new one, as below:
<div class="avatar-view" title="" data-original-title="Change the avatar">
<img src="../../scripts/cropper/img/20150728143117.png" alt="Avatar">
</div>
Underneath the avatar is the user form with the rest of the details and a save/submit button. I have added a hidden field for the avatar, but I need to send the value of the newly uploaded image to this hidden field. I have looked for various pieces of javascript/jquery to do this but I can't seem to get it to work so far.
<form id="reg-form" name="r_form" method="post" action="/editor/go/user" enctype="multipart/form-data">
<div class="form-group">
<label for="avatar">avatar</label>
<input type="hidden" name="avatar" value="123">
</div>
<div class="form-group">
<label for="first_name"><i class="fa fa-star icon-red"></i> First name</label>
<input id="first_name" name="first_name" class="form-control" value="John">
</div>
<div class="form-group">
<label for="last_name"><i class="fa fa-star icon-red"></i> Last name</label>
<input id="last_name" name="last_name" class="form-control" value="Smith">
</div>
<button type="submit" class="btn btn-primary" name="form_submit" tabindex="15">Save</button>
<input type="hidden" name="user_id" value="41">
</form>
First add an id to the hidden input value,
<input id="avatar-val" type="hidden" name="avatar" value="123">
then execute this code when the button is clicked
$("#avatar-val").val($(".avatar-view>img").prop('src'));
Get the link to current image using query and set it to hidden field.
<div class="form-group">
<label for="avatar">avatar</label>
<input type="hidden" name="avatar" value="123">
</div>
<script>
var src = $('.avatar-view').find('img').attr('src');
$('input[name="avatar"]').attr('src', src)
</script>
Without any modification you can use like
var src=$('img[alt="Avatar"]').attr('src');
$('input:hidden[name=avatar]').val(src);
$(document).ready(function(){
$('#reg-form').submit(function() {
var newSrc = $('#ID_of_your_img').attr('src');
$('[name=avatar]').val(newSrc);
});
});
I hope this will help you. if you face any issue feel free to ask.
Your img tag needs to have an id. Then you can simply use the DOM to change the src. Then you can tie a Javascript function to the onclick attribute of the submit button.
<img id="change" src = "....">
...
<button type="submit" onclick="changeImage()" class="btn btn-primary" name="form_submit" tabindex="15">Save</button>
<script>
function changeImage(){
src = document.getElementById("change").src ;
document.getElementsByName("name")[0].value - src;
}
</script>

Remove html element from a page loaded as ajax response into div

I am trying to remove a link(I want to make this as button please help in that too) with id=regbutton as soon as my index.jsp page is loaded as a response on clicking login button on regdata.jsp page
regdata.jsp
<script>
$(document).ready(function(){
$("button").click(function(){
$("#mainDiv").load("index.jsp");
$('#regButton').remove();
});
});
</script>
</head>
<body>
<div id="mainDiv" class="units-row">
<h2>Thanks For registering!</h2>
<button id="regLogin">Login Now</button>
</div>
index.jsp
<body>
<center>
<s:actionerror />
<h1 id="login_title"></h1>
<form action="checkLogin.action" method="post">
<p>
<input type="text" id="username" name="username"
placeholder="" >
</p>
<p>
<input type="password" name="password"
placeholder="" id="password">
</p>
<label> <input type="checkbox" name="remember_me" id="remember"><label for="remember" id="rememberlbl"></label></label>
</p>
<input type="submit" class="btn-log" method="execute"
key="label_login">
</form>
Register
</center>
</body>
The jQuery's load function takes a second or third parameter - a callback function to execute when loading is done. So if you want the button to disappear only when the load completes you should move your code for it into that handler:
$(document).ready(function(){
$("button").click(function(){
$("#mainDiv").load("index.jsp", function() {
$('#regButton').remove();
});
});
});
I can see a simple solution
#regButton
{
display:none;
}
If this ain't sufficient i am working on a jquery solution as well

Jquery how to check checkbox on div click, change class and show div

I am trying to checkbox when the div.menuitem is clicked and then it should change class and show the content in the div with class of hidediv. When the div.menuitem is again clicked it should remove the class and hide the div again and uncheck the checkbox.
Want I want to do:
Only show the content of the hidediv when the menuitem is pressed. (checkbox should be checked)
When the menuitem is pressed the checkbox should be checked
When the menuitem is clicked again the hidediv should be hidden again. (checkbox unchecked)
And the checkbox should be uncheched
Illustration of my menu form:
<div class="menuitem">
1.Company1
</div>
<div class="hidediv">
1.1 Company 1.1
1.2 Company 1.2
</div>
<div class="menuitem">
1.Company2
</div>
<div class="hidediv">
1.1 Company 2.1
1.2 Company 2.2
</div>
My previous Jquery code, which only is trigger when the checkbox is clicked. I want pretty
similar function to this, the checkbox should also be trigghed when the div is clicked:
$('.menuitem input:checkbox').change(function(){
if($(this).is(':checked')) {
$('div.hidediv').addClass('someclass').show(200); // not needed it there is another way of identifying the div later to add to hidediv class again.
$('div.hidediv').removeClass('hidediv');
} else {
$('div.someclass').addClass('hidediv').hide(200);
}
});
});
My Jquery so far(not working):
$('.menuitem').click(function(e){
$(this).addClass('menuclicked');
$('div.hidediv').addClass('clicked').show(200);
$('div.hidediv').removeClass('hidediv');
} else {
$('div.someclass').addClass('hidediv').hide(200);
}
$('.menuclicked').click(function(e){
$('div.someclass').addClass('hidediv').hide(200);
});
My HTML:
<form accept-charset="UTF-8" action="/" method="get"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /></div>
<div class="menuitem">
<label for="search_company1">company1</label>
<input name="search[company1_is_true]" type="hidden" value="0" /><input id="search_company1_is_true" name="search[company1_is_true]" type="checkbox" value="1" />
</div>
<div class="menuitem">
<label for="search_company3">company3</label>
<input name="search[company3_is_true]" type="hidden" value="0" /><input id="search_company3_is_true" name="search[company3_is_true]" type="checkbox" value="1" />
</div>
<div class="hidediv">
<div class="menuitem">
<label for="search_company2">company2</label>
<input name="search[company2_is_true]" type="hidden" value="0" /><input id="search_company2_is_true" name="search[company2_is_true]" type="checkbox" value="1" />
<div>
</div>
<input id="search_submit" name="commit" style="display:none;" type="submit" value="Submit" />
</form>
I can help. I think you are structuring this wrong. You have three fields in your html, with the third being hidden. I assume when you fill in the first one you want nothing to happen, but clicking the second one should show the third field?
Try this:
//Use toggle instead of .click()
$('.menuitem').toggle(function(){
$('div.hidediv').addClass('clicked').show(200);
}, function(){
$('div.hidediv').removeClass('clicked').hide(200);
});
This will effect all divs with the "menuitem" class, meaning when you click on any of the three it will toggle showing/hiding the div with the "hidediv" class.
edit you have a couple valid answers here, but I think you're approaching this wrong. If you go try the jsfiddle posted by another user, whos' javascript does the same as mine - it reveals the problem I talked about above. You cannot select all three boxes without some clever clicking. Each click will toggle showing/hiding the third check box. Might I suggest modifying your code like so:
//Use toggle instead of .click()
$('.toggleMenuItem').toggle(function(){
$('div.hidediv').addClass('clicked').show(200);
}, function(){
$('div.hidediv').removeClass('clicked').hide(200);
});
<form accept-charset="UTF-8" action="/" method="get">
<div style="margin:0;padding:0;display:inline">
<input name="utf8" type="hidden" value="✓" />
</div>
<div class="menuitem">
<label for="search_company1">company1</label>
<input name="search[company1_is_true]" type="hidden" value="0" />
<input id="search_company1_is_true" name="search[company1_is_true]" type="checkbox" value="1" />
</div>
<div class="menuitem toggleMenuItem">
<label for="search_company3">company3</label>
<input name="search[company3_is_true]" type="hidden" value="0" />
<input id="search_company3_is_true" name="search[company3_is_true]" type="checkbox" value="1" />
</div>
<div class="hidediv">
<div class="menuitem">
<label for="search_company2">company2</label>
<input name="search[company2_is_true]" type="hidden" value="0" />
<input id="search_company2_is_true" name="search[company2_is_true]" type="checkbox" value="1" />
<div>
</div>
<input id="search_submit" name="commit" style="display:none;" type="submit" value="Submit" />
</form>
This will make it so only clicking the checkboxes with the class ".toggleMenuItem" will show the third checkbox.
try something like this:
$('.menuitem').click(function(e){
if($(this).hasClass('menuClicked')){
// Already clicked
$(this)
.removeClass('menuclicked')
.html("");
}else{
// First click
$(this)
.addClass('menuclicked');
.html($('#hidediv').html());
}
})
This may do what you're looking for:
$('.menuitem').click(function(e){
$(this).toggleClass('clicked');
$('div.hidediv').toggle(200);
});
Let me know if it is missing a feature.
http://jsfiddle.net/citizenconn/2bCdR/

Using the same input box to search different things

I have an input which searcher's google web and another input to search google images. For each input i have buttons to fadeIn either. Can the search input be the same but search different sites?
Here is a fiddle of what I currently have: http://jsfiddle.net/kwC36/
To search the web I use:
<form action="http://google.com/search" method="get" class="websearch">
and to search images I use:
<form action="http://www.google.com/images?hl=en&q=" method="get" class="imagesearch">
Thanks alot
Yeah, you can switch action on the form:
$('.web').click(function(){
$('form')[0].action = "http://google.com/search";
// do something
$('.websearch').fadeIn();
});
$('.image').click(function(){
$('form')[0].action = "http://www.google.com/images?hl=en&q=";
// do something
$('.websearch').fadeIn();
});
Assign custom data attributes to the button so the form action can be dynamic:
HTML:
<form id="search-form" action="" method="get" class="websearch">
<input id="search-field" type="text" class="searcher" name="" />
</form>
<input type="button" value="Search the web" class="search-btn" data-action="http://google.com/search" data-field-name="" />
<input type="button" value="Search images" class="search-btn" data-action="http://www.google.com/images?hl=en&q=" data-field-name="q" />
JQuery:
$('.search-btn').click(function(e){
e.preventDefault();
$('#search-field').attr('name',$(this).data('field-name'));
$('#search-form').attr('action',$(this).data('action')).submit();
});
<input type="submit" name="srch_images" value="Search Images">
<input type="submit" name="srch_google" value="Search Google">
if( isset($_POST['srch_images'] )
{
something();
}
else if( isset($_POST['srch_google']) )
{
something_else();
}
You can use the same textbox to search for web and image. Also there is no need to have two form tags. Try this
$('.web').click(function(){
$('form').attr('action', "http://google.com/search").submit();
});
$('.image').click(function(){
$('form').attr('action', "http://www.google.com/images?hl=en&q=").submit();
});
HTML:
<form action="http://google.com/search" method="get" class="websearch">
<input type="text" class="searcher">
<input type="submit" value="Web Search" class="web">
<input type="submit" value="Image Search" class="image">
</form>
Javascript:
$('.image').click(function() {
$(this).parent()
.attr('action', 'http://www.google.com/images?hl=en&q=');
});
That should do it.

Categories

Resources