jquery hide/show form elements, preventing slip of elements - javascript

I use the following code to show some forms, when a certain element is selected from the select input.
javascript:
$(document).ready(function() {
$( "#callback_url" ).hide();
$("#test-url").on("change keyup paste", function(){
//console.log($("#test-url").val());
//generate address
if ($("#test-url").val() == 0) {
console.log("true");
$( "#callback_url" ).hide();
$( "#api_key" ).show();
}
//payload
else{
console.log("else");
$( "#api_key" ).hide();
$( "#callback_url" ).show();
}
})
});
My HTML code looks like this (using bootstrap):
<div class="row">
<div class="col-md-4">
<div class="form-group">
<select class="form-control" id="test-url" size="5">
<option selected value="0">Generate new address</option>
<option value="1">Receive callback</option>
<option></option>
</select>
</div>
</div>
<div class="col-md-8">
<form id="test-form">
<div class="form-group" data-url="/api/receive?method=create">
<input type="text" id="api_key" class="form-control" name="api_key" placeholder="API-Key">
</div>
<div class="form-group test-specific-inputs" data-url="/api/receive?method=check_logs">
<input type="text" id="callback_url" class="form-control" name="callback_url" placeholder="Callback URL">
</div>
<div class="form-group">
<button type="submit" class="btn-info btn-lg">Send Request</button>
</div>
</form>
</div>
</div>
All in all I've got two questions:
1.) Is it good style to use javascript at the top of document ready to hide the element, when page is loaded? If not, what to use instead of?
2.) When I load the page the first time it looks like
Now when clicking "Receive callback" it looks like:
How is this caused, and how can I prevent the input form to "slip" down like it does, when changing the selected element?

1) Using $(document).ready waits for the page to load and this means that the javascript code inside that function will run once the HTML has finished loading and rendering. This is useful when you are working with HTML elements from your JS code. I would suggest using $(document).ready to make sure you can place all you script libraries in the <head> and know that there won't be a chance of an undefined element that was yet to be rendered.
2) I used your exact code with bootstrap 3.3.7 and it seems to work fine, so I think there is a problem with your parts of your HTML or CSS that you didn't include here. See for yourself:
$(document).ready(function() {
$( "#callback_url" ).hide();
$("#test-url").on("change keyup paste", function(){
//console.log($("#test-url").val());
//generate address
if ($("#test-url").val() == 0) {
console.log("true");
$( "#callback_url" ).hide();
$( "#api_key" ).show();
}
//payload
else{
console.log("else");
$( "#api_key" ).hide();
$( "#callback_url" ).show();
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ></script>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<select class="form-control" id="test-url" size="5">
<option selected value="0">Generate new address</option>
<option value="1">Receive callback</option>
<option></option>
</select>
</div>
</div>
<div class="col-md-8">
<form id="test-form">
<div class="form-group" data-url="/api/receive?method=create">
<input type="text" id="api_key" class="form-control" name="api_key" placeholder="API-Key">
</div>
<div class="form-group test-specific-inputs" data-url="/api/receive?method=check_logs">
<input type="text" id="callback_url" class="form-control" name="callback_url" placeholder="Callback URL">
</div>
<div class="form-group">
<button type="submit" class="btn-info btn-lg">Send Request</button>
</div>
</form>
</div>
</div>
Cheers

Related

JQuery on('click') does not work when clicked

So I'm currently working on this project and I am stuck this problem. I tried looking at the console but it doesn't show anything when I clicked the button. What I'm trying to do is when I click the button, it will trigger the file input, but so far, when I clicked it, nothing happens, not even an error is shown.(The code is based on the answer in this question: Bootstrap form upload file layout) Can you guys help me find out what I did wrong
These are the codes
TabUploadDokumen.html
<script>
$(document).ready(function () {
/* Some code here */
});
$('#btn_IdentitasKTP/Paspor').on('click', function () {
$('#file_IdentitasKTP/Paspor').trigger('click')
});
$('#file_IdentitasKTP/Paspor').change(function () {
var file_name = this.value.replace(/\\/g, '/').replace(/.*\//, '');
$('#text_IdentitasKTP/Paspor').val(file_name);
});
</script>
<!--Some other code -->
<div class='form-group'>
<label class='control-label'>Nama Dokumen<br /><span style='font-weight:normal;'>Silahkan scan/foto dokumen Anda disini</span></label>
<div class='form-group'>
<label for="text_IdentitasKTP/Paspor" id="lbl_IdentitasKTP/Paspor" class="control-label">Identitas(KTP/Paspor)</label>
</div>
<div class="input-group">
<input type="file" id="file_IdentitasKTP/Paspor" name="name_file_IdentitasKTP/Paspor" accept="image/jpg,image/jpeg,application/pdf,image/png" style="display: none" />
<input type="text" class="form-control" id="text_IdentitasKTP/Paspor" readonly />
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="btn_IdentitasKTP/Paspor">Upload KTP/Paspor</button>
</span>
</div>`
</div>
<!-- Some other code -->
I'm using ASP.NET MVC 5 and Bootstrap version 3.00 and Jquery version jquery version 1.11.1 if it is any help.
Thanks in advance
Your selectors contain forward slashes that need to be escaped like this:
$("#btn_IdentitasKTP\\/Paspor'")
Ensure that your jQuery code is sat within your document.ready() function.
Escape the selectors that contain forward slashes (click here for more)
I would also replace
$('#btn_IdentitasKTP/Paspor').on('click', function () {
with
$('document').on('click','#btn_IdentitasKTP\\/Paspor', function () {
The on('click') function needs to run in the $(document).ready function, otherwise it will run before the DOM is ready and won't find the element it's supposed to bind to.
$(document).ready(function () {
$('#btn_IdentitasKTP\\/Paspor').on('click', function () {
$('#file_IdentitasKTP\\/Paspor').trigger('click')
});
});
(And escape the slashes as suggested in another answer)
it doesn't work because script tag is render before the html elements. it will work if you change the code as below,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--Some other code -->
<div class='form-group'>
<label class='control-label'>Nama Dokumen<br /><span style='font-weight:normal;'>Silahkan scan/foto dokumen Anda disini</span></label>
<div class='form-group'>
<label for="text_IdentitasKTP_Paspor" id="lbl_IdentitasKTP_Paspor" class="control-label">Identitas(KTP/Paspor)</label>
</div>
<div class="input-group">
<input type="file" id="file_IdentitasKTP_Paspor" name="name_file_IdentitasKTP_Paspor" accept="image/jpg,image/jpeg,application/pdf,image/png" style="display: none" />
<input type="text" class="form-control" id="text_IdentitasKTP_Paspor" readonly />
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="btn_IdentitasKTP_Paspor" >Upload KTP/Paspor</button>
</span>
</div>`
</div>
<script>
$(document).ready(function () {
/* Some code here */
});
$('#btn_IdentitasKTP_Paspor').on('click', function () {
$("#file_IdentitasKTP_Paspor").click()
});
$('#file_IdentitasKTP_Paspor').change(function () {
var file_name = this.value.replace(/\\/g, '/').replace(/.*\//, '');
$('#text_IdentitasKTP_Paspor').val(file_name);
});
</script>
<!-- Some other code -->

.click() function doesn't work javascript / jquery

UPDATE:
Somehow the just work fine after I tried it..
UPDATE
I'm using .click() function on my javascript, but it doesn't work.
Here is my JS code:
src="jquery.js";
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
var institutionID, acadCareerID;
$(document).ready(function(){
getInstitution();
institutionID = $( "select#institution option:checked" ).val();
if(institutionID == null){
institutionID = 1;
}
getAcadCareerByInstitution(institutionID);
acadCareerID = $( "select#acadCareer option:checked" ).val();
if(acadCareerID == null){
acadCareerID = 1;
}
getPeriodByAcadCareerAndInstitution(acadCareerID);
getDepartmentByAcadCareer(acadCareerID);
$("select#institution").change(function(){
institutionID = $( "select#institution option:checked" ).val();
getAcadCareerByInstitution(institutionID);
})
$("select#acadCareer").change(function(){
acadCareerID = $( "select#acadCareer option:checked" ).val();
getPeriodByAcadCareerAndInstitution(acadCareerID);
getDepartmentByAcadCareer(acadCareerID);
})
$("div#search").click(function(){
alert("The paragraph was clicked.");
console.log("abc");
});
});
all functions like getInstituion(), getAcadCareerByInstitution(institutionID) etc are ajax call.
Here is my HTML code:
<form action="doInsertSchedule" method="POST" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for="institution">Institution</label>
<select name="institution" class="form-control" id="institution">
</select>
</div>
<div class="form-group">
<label for="acadCareer">Academic Career</label>
<select name="acadCareer" class="form-control" id="acadCareer">
</select>
</div>
<div class="form-group">
<label for="period">Period</label>
<select name="period" class="form-control" id="period">
</select>
</div>
<div class="form-group">
<label for="department">Department</label>
<select name="department" class="form-control" id="department">
</select>
</div>
<div class="form-group">
<label for="date">Deadline Date</label>
<input type="date" class="form-control" id="deadline" placeholder="Deadline Date" name="deadline">
</div>
<button type="submit" class="btn btn-default">Submit</button>
<div id="search" class="btn btn-default">Search</div>
</form>
I already put jquery for my Master Layout (Laravel 5)
<head>
<link rel="stylesheet" type="text/css" href="{{url()}}/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="{{url()}}/css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="{{url()}}/js/tools.js"></script>
<script src="{{url()}}/js/bootstrap.min.js"></script>
<title>BINUS - #yield('title')</title>
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
I want the Search Button / Div to do something when I click. I can't see what's wrong here.
I already tried <div> to <button> but it just will work like submit. I also already tried to put event.preventDefault() at my JS code, but it didn't work too.
Maybe you can try with event delegation...
$(document).ready(function(){
$("body").on("click", "#search", function(){
alert("The paragraph was clicked.");
console.log("abc");
});
});
You code works OK. You need to write the jquery library in the final, just before of </body>
...
<script type="text/javascript" src=".../jquery.js"></script>
</body>
Example it works ok!: Example Jsfiddle
<button type="submit" class="btn btn-default">Submit</button>
<div id="search" class="btn btn-default">Search</div>
This looks like it will render on the page as two buttons. Your ID here is attached to the div, not to the button, they should both appear to look like buttons providing bootstrap is loaded, but only the div with "search" as the content will do anything.
This is the only thing that appears odd, the only other problem is you are not loading your jquery as stated elsewhere.
I don't have the reputation to comment, but have you added a jquery library before your script?
Secondly, if you did and the items on the page are loaded after the document has loaded you will need to change your code up, for instance:
Give your form an id
<form action="doInsertSchedule" method="POST" enctype="multipart/form-data" id="postForm">
Then in your jquery script
<script>
$('#postForm').on('click', '#search', function(){
alert("The paragraph was clicked.");
console.log("abc");
});
</script>
The above will allow the javascript to run on items that are bought in after document load, however it is important you set it on a parent element that is avaiable at document load

Cannot read property 'settings' of undefined when I click submit button

I don't know why I received this error when I changed the code to php (from html). when the extension of the file is html, the code is working fine.
<?php?>
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="css/manual.css">
<!-- Optional theme -->
<!-- Latest compiled and minified JavaScript -->
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<title>Register</title>
</head>
<body>
<nav class="navbar navbar-default" id="navBar">
</nav>
<div class="full">
<div class="col-xs-12">
<!--Side Bar-->
<div class="col-xs-3" id="navSide">
</div>
<div class="col-xs-6" id="signUpForm">
<h1>Register Page</h1>
<form role="form" id="signUpForm">
<div class="form-group">
<div class="form-inline spacer-12">
<input type="text" class="form-control" name="userFirstname" placeholder="First Name">
<input type="text" class="form-control" name="userLastName" placeholder="Last Name">
</div>
</div>
<div class="form-group ">
<input type="text" class="form-control"
name="userEmail"
placeholder="Email">
</div>
<div class="form-group ">
<input type="password" class="form-control" name="userPassword" placeholder="Password">
</div>
<div class="form-group ">
<input type="password" class="form-control" name="confirmPassword" placeholder="Password">
</div>
<div class="form-group ">
<label> Birthday* </label>
<input type="date" class="form-control" name="userBirthday" placeholder="Birthday">
</div>
<input type="submit" class="btn btn-info spacer-12" style="clear:both" >
</form>
</div>
</div>
</div>
<script src="js/startup.js"></script>
<script src="js/signup.js"></script>
</body>
</html>
<?php?>
then this is my jquery validation code
$(document).ready(function(){
$('#signUpForm').validate({
errorElement: "span",
errorClass: "help-block",
rules:{
userFirstName:{
required: true
},
userLastName:{
required: true
},
userEmail:{
required: true
},
userPassword:{
required: true
},
confirmPassword:{
required: true
},
userBirthday:{
required: true
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error').addClass('red-border');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error').addClass('has-success').removeClass('red-border');
}
});
});
This code causes error when I click the submit button (JQuery Validate Uncaught TypeError: Cannot read property 'settings' of undefined )
But the error is temporary and will vanish in a while.
You defined two ids with same name, whereas id should be unique.
<div class="col-xs-6" id="signUpForm">
<form role="form" id="signUpForm">
Try to remove id from <div class="col-xs-6" id="signUpForm">
If you use the rules() method, make sure to initialize the validation first.
var validator = $("#Form1").validate();
$('#field1').rules("add", {
min: 1
});
This error is normally caused by trying to validate an element that is not a form. In the OP's case, there are two elements with the same ID:
<div class="col-xs-6" id="signUpForm">
<form role="form" id="signUpForm">
jQuery searches a page from top to bottom, and the first element it finds with this ID is not a form.
The Validator.element() function (for validating single elements) can also cause this error, if attempting to validate an element that is outside the form.
NOTE two things
1. Define the Jquery function
include the function of jQuery !
(function( $ ) {
//Start Script
//endscript/
})( jQuery );
Change the Form Id because it's doing conflict between Form Id and Div Id
<form role="form" id="signUpForm1"> // include 1 in previous form id
And put this id into script
$('#signUpForm1').validate({ // put the Id in the script
Hope Your Task will be successful.
To add a small detail here, I ran into the same problem with jQuery UI time picker, and it also was due to the id being non-unique.
In my case, it's because I was grabbing the parent element from a template - duplicating it for a pop-up window. As a result, the contents of the window all had duplicate ids.
My normal workaround for that was to replace this:
$('#foo').bar();
with this:
myPopupWindow.find('#foo').bar();
That works quite well for most things, but not for the time picker. For that one, I wound up doing this:
myPopupWindow.find('#foo').attr('id', 'foo_' + someUniqueTag);
myPopupWindow.find('#foo_' + someUniqueTag).timepicker();
where someUniqueTag is a record id, random number or some other distinct string. This solved it quite nicely for me.

Jquery Validation Plugin not working in Jquery ui custom dialog box

I am using validate.js library given on this link http://jzaefferer.github.io/jquery-validation/jquery.validate.js to validate the text fields of pop-up form made using Jquery custom dialog box.
Whenever i click in the submit button,i keep getting the error"validate not defined"..I can't understand whats wrong with my code..
I want the plugin to validate all the fields given in the pop-up form...
Please Help..
Code..
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Dialog - Animation</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<script src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"> </script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script type= text/javascript>
$(function() {
$( "#dialog1" ).dialog({
autoOpen: false,
modal: true,
resizable: false,
width:800,
height:800,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
}
});
$( "#opener" ).click(function() {
$( "#dialog1" ).dialog( "open" );
});
});
$(document).ready(function(){
$("#dialog").validate();
});
function isNumberKey(evt){ <!--Function to accept only numeric values-->
//var e = evt || window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
<style>
textarea {
vertical-align: top;
}
</style>
</head>
<body>
<div id="dia">
<form name="dialog" method="get" action="">
<div id="dialog1" title="Upload Details">
<fieldset>
<legend><p>Please fill in the follwing Item details to compalete the uploading process.</p></legend><br><br>
Name: <input type="text" id="cIname" name="Iname"size="30" placeholder="Item Name"/><br><br>
<p><div id='ccontactform_category_errorloc' class='err'></div>
<label for="ccategory" style="margin-bottom: 90px;margin-top:50px">Category: </label>
<select id="ccategory" name="category"class="input">
<option value="0" selected="selected">
[Choose Category]
</option>
<option value="Arts and entertainment">Arts and entertainment</option>
<option value="Automotive">Automotive</option>
<option value="Business">Business</option>
<option value="Computers">Computers</option>
<option value="Games">Games</option>
<option value="Health">Health</option>
<option value="Internet">Internet</option>
<option value="News and Media">News and Media</option>
<option value="Recreation">Recreation</option>
<option value="Reference">Reference</option>
<option value="Shopping">Shopping</option>
<option value="Sports">Sports</option>
<option value="World">World</option>
</select>
<div id="choose_own_text"></div>
</p><br>
Brand: <input type="text" id="cIbrand" name="Ibrand" size="30" placeholder="Item Brand"/><br><br>
Price (Rs): <input type="text" name="price" id="cprice"size="20" placeholder="Enter Price" maxlength="15" onkeypress="return isNumberKey(event)"/> .00 ps<br><br>
<label for="cIdescrp" style="margin-bottom: 90px;margin-top:50px">Description:</label>
<textarea rows="15" cols="40" id="cIdescrp" name="Idescrp"style="resize: none;overflow:auto" onkeypress=""></textarea><br><br>
Mobile No: <input type="text" name="Num" id="cNum"size="20" placeholder="Enter Valid Number" maxlength="10" onkeypress="return isNumberKey(event)"/> <br><br>
<button id="Submit" onclick="validate()">Submit Details</button>
</fieldset>
</div>
</form>
<button id="opener">Open Dialog</button>
</div>
</body>
</html>
Quote OP:
I keep getting the error "validate not defined".
It sounds like you have not properly included the Validate plugin script:
<script src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"> </script>
Instead of linking directly to the Github file, use the CDN link provided by the developer for this purpose:
http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js
Also include type="text/javascript" to make it valid HTML:
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
And of course, your jQuery selector target, $("#dialog"), is incorrect. The hash, #, is trying to target an id which does not exist.
Either add id="dialog" to your form tag...
<form id="dialog" name="dialog" method="get" action="">
OR change your selector to target the element by its name attribute...
$('[name="dialog"]').validate();
Your code:
<button id="Submit" onclick="validate()">Submit Details</button>
Do not use inline JavaScript. With jQuery, inline JavaScript is ugly and obsolete. In this case, there is no practical needs to call .validate() again. It's the initialization for the plugin and only needs to be called once on DOM ready; you've already done that.
Use this:
<button id="Submit">Submit Details</button>
See demo below for how to declare rules. In demo, I used your code and applied required to the first field. Fields are identified by name attribute. To make a select list required, the first option item must contain value="".
Working DEMO:
http://jsfiddle.net/aqJVm/
I strongly suggest that you thoroughly review the documentation:
http://docs.jquery.com/Plugins/Validation

jQuery Mobile Show/Hide Form input based on select field

I have the following form fields on my jQuery Mobile page. I want to initially hide the element, and then have it .show() if the user selects the option with value="Other"
Here's my HTML:
<div data-role="fieldcontain" class="no-field-separator">
<select name="plan_height" id="plan_height" data-native-menu="false">
<option>Plan Height</option>
<option value="Standard 6foot 2inch">Standard 6'2"</option>
<option value="Other">Specify in Notes</option>
</select>
</div>
<div id="specify_plan_height_box" style="display:none;">
<div data-role="fieldcontain" class="ui-hide-label no-field-separator">
<label for="specify_plan_height">Specify Plan Height</label>
<input type="text" id="specify_plan_height" name="specify_plan_height" placeholder="Specify Plan Height" maxlength="50" />
</div>
</div>
and here's my JS INSIDE the page:
// $( '#machine-guarding-page' ).live( 'pageinit',function(event) {
$( document ).bind( "pageinit", function( event, data ) {
$('#plan_height').change(function() {
var planHeightVal = $("#plan_height option:selected").val();
var sphb = $("#specify_plan_height_box");
sphb.hide();
if (planHeightVal == "Other") {
sphb.show();
}
});
});
});
It works fine here in this working example. Do I need to have something other than $(".page").live('pageinit', function() {
at the top of my JS code to make it work after the page loads? It works fine in the example link above, but not on my jQuery Mobile site.
Does this work for you:
http://jsfiddle.net/Qe6G4/1/
http://jsfiddle.net/Qe6G4/2/ (optimized)
http://jsfiddle.net/Qe6G4/3/ (with another input)

Categories

Resources