I'm trying to hide a div when the value = 10
Here is the code and demo working fine:
<script>
$('input[name=test]').keyup(function(){
if($(this).val()<10)
$('#yeah').show();
else
$('#yeah').hide();
});
</script>
<label>Type whatever</label>
<input type="text" name="test"value="10" />
<div id="yeah" style="display:none;">
<input type="submit" />
</div>
But I'm trying to convert that code into Prototype code and I tried this code:
Event.observe(window, 'load', function () {
$('input[name=test]').keyup(function(){
if($(this).val()<10)
$('#yeah').show();
else
$('#yeah').hide();
});
});
I only want to hide the div when input value = 10 into prototype code.
Please somebody can help me?
Give the textbox an ID. For example:
<input type="text" id="txtbox" name="test" value="10" />
Change:
<div id="yeah" style="display:inline;">
To:
<div id="yeah" style="display:none;">
You need to use the $$ function which returns an array.
Event.observe('txtbox', 'keyup', function () {
if ($$('input[name="test"]')[0].value < 10){
$$('#yeah')[0].show();
}
else{
$$('#yeah')[0].hide();
}
});
Note: You could also use .first() instead of [0]
JSFiddle
you have a issue with prototype lib,
the Event.observe function is never triggered, secondly, you seem to still using the jquery api
$().keyup()
and you only load the prototype function.
Now days people rarely uses prototype, people use jquery for dom and underscore/lodash for iterations.
Related
I'm an absolute beginner and tried to find similar questions but couldn't. Apologies if this has been answered previously.
In my assignment we need to create a form with 2 text fields and 1 button. The fields are for height and width and the idea is that onclick on the button will send the 2 parameters to a function that will change the height + width attributes for a photo. I know I'm doing something wrong because the picture simply disappears. Ideas? Thanks!
<html>
<head>
<script>
function borderResize(height1, width1)
{
document.getElementById('Amos').height = height1;
document.getElementById('Amos').width = width1;
}
</script>
</head>
<body>
<img src="Amos.jpg" id="Amos" />
<form>
<input type="text" id="height" placeholder="Height" />
<input type="text" id="width" placeholder="Width" />
<input type="button" value="click!" onclick="borderResize('height.value', 'width.value')"/>
</form>
</body>
</html>
When you write
onclick="borderResize('height.value', 'width.value')"
in means that on click borderResize function will be invoked with two string arguments, literally strings "height.value" and "width.value". In your case you want something like this
onclick="borderResize(document.getElementById('height').value, document.getElementById('width').value)"
In above case you are selecting element from DOM using getElementById method and then read its value property.
You should learn to use addEventListener(), I would recommend you not to use ugly inline click handler.
The EventTarget.addEventListener() method registers the specified listener on the EventTarget it's called on.
Here is an example with your code.
window.onload = function() {
document.getElementById('button').addEventListener('click', borderResize, true);
}
function borderResize() {
document.getElementById('Amos').height = document.getElementById('height').value;
document.getElementById('Amos').width = document.getElementById('width').value;
}
<img src="https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpf1/v/t1.0-1/s200x200/11034289_10152822971918167_2916173497205137007_n.jpg?oh=71de7a46a75a946cf1d76e5ab10c1cdc&oe=55889977&__gda__=1434173455_6127f174627ed6014c84e562f47bc44c" id="Amos" />
<input type="text" id="height" placeholder="Height" />
<input type="text" id="width" placeholder="Width" />
<input type="button" id="button" value="click!" />
However as for your immediate problem you can use
onclick="borderResize(document.getElementById('height').value, document.getElementById('width').value)"
onclick="borderResize('height.value', 'width.value')"
here you pass to borderResize strings: 'height.value', 'width.value'.
You may get value of input from function:
function borderResize(height1, width1)
{
document.getElementById('Amos').height = document.getElementById('height').value;
document.getElementById('Amos').width = document.getElementById('width').value;
}
I am receiving the following error in my console:
Uncaught TypeError: Cannot read property ‘value’ of null
What I'm attempting to do is copy text input from one input box into another, when you click the checkbox the value of one input will be copied into another input.
HTML
<input name="stry" type="text" id="stry"/>
<input type="checkbox" name="sendsms" onclick="CopyStory(this.form)">
<div id="container">
<input type="text" class="form-control" name="body">
</div>
JS
function CopyStory(f) {
if(f.sendsms.checked == true) {
f.stry.value = f.body.value;
}
}
I believe the problem is that the code is executed before the elements load because I have a javascript alert modal pop-up which prevents the page from loading unless you press 'Ok'
Alert JS
$('#container').fadeOut('fast').delay(7000).fadeIn('fast');
alert("This page is loading....");
I've tried wrapping it around document.ready(function blah... but then it gives me an error that: " 'CopyStory' is not defined".
Any suggestions?
Take a look at this JSFiddle.
JS
function copyStory(ch) {
if(ch.checked)
var text1 = document.getElementById("stry").value;
else
text1='';
document.getElementById("second").value = text1;
}
$('#container').fadeOut('fast').delay(7000).fadeIn('fast');
alert("This page is loading....");
HTML
<input name="stry" type="text" id="stry"/>
<input type="checkbox" name="sendsms" onclick="copyStory(this)">
<input type="text" class="form-control" id="second" name="body">
<div id="container">
</div>
You are not using the form tags and trying to access a form..!
Try this,
function CopyStory(f) {
if(f.sendsms.checked == true) {
console.log(f.body.value);
f.stry.value = f.body.value;
}
}
<div>
<form>
<input name="stry" type="text" id="stry"/>
<input type="checkbox" name="sendsms" onclick="CopyStory(this.form)">
<div id="container">
<input type="text" class="form-control" name="body">
</form>
</div>
Just put the js script inside <head></head>
First, wrap your code in $(function(){ //code here }); to execute your js after page loads.
About 'CopyStory' is not defined:
when you define function like:
$(function(){
function CopyStory(){ //... }
});
CopyStory is not visible in global scope, so if you want to fix your problem just change defenition to:
$(function(){
window.CopyStory = function(){ //... }
});
p.s. assign a variable to window propery is the only way to define global variable inside a local scope.
My JS is as follows:
$(document).ready(function(){
$('#data1').change(function(){
title = $('#title1').val();
url = $('#url1').val();
$.post('library/edit.php',{title:title, url:url},function(res){
alert ("updated !");
});
});
});
and my HMTL-markup:
<div id="data1">
<input name="title1" type="text" id="title1" />
<input name="url1" type="text" id="url1" />
</div>
I wrote that code to call to a PHP file on change of textbox.
that code works as expected.
But now I've added more textboxes as follows:
<div id="div1"><input name="title1" type="text" id="title1" />
<input name="url1" type="text" id="url1" /></div>
<div id="div2"><input name="title2" type="text" id="title2" />
<input name="url2" type="text" id="url2" /></div>
<div id="div3"><input name="title3" type="text" id="title3" />
<input name="url3" type="text" id="url3" /></div>
Now I want the same functionality so that any of these textboxes works like title1 in my earlier code. So if input#title-3 is changed I want the change to be uploaded via POST to my PHP-script.
Important: The number of boxes are dynamic.
$(document).ready(function(){
$('#data1').on('change','[id^=title],[id^=url]',function(){
var index = $(this).attr('id').replace('title',"").replace('url',"");
var title = $("#title" + index).val();
var url = $("#url" + index).val();
var hid = $("#hid" + index).val();
// you can put in here in sequence all the fields you have
$.post('library/edit.php',{title:title, url:url, hid : hid},function(res){
alert ("updated !");
});
});
});
so by this answer if any text box whoes id starts with title changes.
the function passed in will be invoked.
indezx variable will store the index of the group of the elements that are changing. and then is being callculated by removing title from title1 or title2
I think the answer you have it right here:
I wrote that code to call to php file on change of textbox.
That script (jQuery I guess) it must be associatte with the $('#xxx1').onchange() right? (or similar)
If you modify the function, add a class to the input field (also in the php) and each time you call the function, start listening again.. I think you can call any function you may want.
Example (guessing your code)
HTML
<div id="data1" class="dynamicDiv">
<input name="title1" type="text" id="title1" />
<input name="url1" type="text" id="url1" />
</div>
jQuery
// enable the function on document ready
$(document).ready(function(){
startListening('.dynamicDiv');
});
// each time an ajax call is completed,
// run the function again to map new objects
$(document).ajaxComplete(function(){
startListening('.dynamicDiv');
});
// and finally the function
function startListening(obj){
$(obj).onchange(function(){
// ajax call
// function call
// or whatever...
});
}
PHP
// some code....
// some code....
// remember here to add "dynamicDiv" as a class in the object
return object;
Since your elements are dynamically generated you need to use event delegation, then you can use [id^="value"] to select the appropriate elements based on the first part of their id attribute
$(document).ready(function(){
$(document).on('change','[id^="data"]',function(){
var title = $(this).find('[id^="title"]').val();
var url = $(this).find('[id^="url"]').val();
var hidden = $(this).find('[id^="hid"]').val();
$.post('library/edit.php',{title:title, url:url, hid:hidden},function(res){
alert ("updated !");
});
});
});
Note: I suggest you bind to the closest parent of your data divs that is present at page load instead of binding to the document
I have a simple form with 2 input fields and one button. When the button is clicked, the value of the 2 input fields should be sent to the AJAX function to be handled in a servlet. For some reason, the servlet is not being reached. Can anyone see why? I have an almost identical method working with a different form, and I can't see why this one isn't working.
Here is the HTML form code:
<div id="addCourses" class="hidden" align="center" >
<form id="addCourse" name="addCourse">
<input type="text" id="courseID" name="courseID" value="courseID" size="40" /><br />
<textarea rows="5" cols="33" id="courseDesc" name="courseDesc">Description</textarea><br />
<input type="button" value="Add Course" onclick="addCourse(this.courseID.value, this.courseDesc.value);"/>
</form>
</div>
Here is the Script function:
<script type ="text/javascript">
function addCourse(id, descr)
{
var fluffy;
fluffy=new XMLHttpRequest();
fluffy.onreadystatechange=function()
{
if (fluffy.readyState==4 && fluffy.status==200)
{
//do something here
}
};
fluffy.open("GET","ajaxServlet?courseID="+id+"&courseDescription="+descr,true);
fluffy.send();
}
</script>
Because this is the button and not the form
so
this.courseID.value
this.courseDesc.value
returns an error.
You should use
this.form.courseID.value
this.form.courseDesc.value
Second problem is you have a name clash. The form and function are named addCourse. It will lead to problems. Rename one of them to be different.
Running Example
When you use this, as in onclick="addCourse(this.courseID.value, this.courseDesc.value);", I think that would refer to the input element, and therefore the values aren't being passed correctly.
Bind your event handlers in javascript, where they should be, and you can avoid the issue entirely.
HTML:
<input type="text" id="courseID" name="courseID" value="courseID" size="40" /><br />
<textarea rows="5" cols="33" id="courseDesc" name="courseDesc">Description</textarea><br />
<input type="button" id="addCourse" value="Add Course"/>
JS:
document.getElementById('addCourse').onclick = function () {
var fluffy = new XMLHttpRequest();
var id = document.getElementById('courseID').value;
var descr = document.getElementById('courseDesc').value;
fluffy.onreadystatechange=function() {
if (fluffy.readyState==4 && fluffy.status==200) {
//do something here
}
};
fluffy.open("GET","ajaxServlet?courseID="+id+"&courseDescription="+descr,true);
fluffy.send();
};
As epascarello pointed out, you need to change the ID of your form as having two elements with the same ID is not allowed and will cause unpredictable javascript behavior.
Try a fluffy.close; after the if ready state expression.
Hello guys i have the below html for a number of products on my website,
it displays a line with product title, price, qty wanted and a checkbox called buy.
qty input is disabled at the moment.
So what i want to do is,
if the checkbox is clicked i want the input qty to set to 1 and i want it to become enabled.
I seem to be having some trouble doing this. Could any one help
Now i can have multiple product i.e there will be multiple table-products divs within my html page.
i have tried using jQuery to change the details but i dont seem to be able to get access to certain elements.
so basically for each table-product i would like to put a click listener on the check box that will set the value of the input-text i.e qty text field.
so of the below there could be 20 on a page.
<div class="table-products">
<div class="table-top-title">
My Spelling Workbook F
</div>
<div class="table-top-price">
<div class="price-box">
<span class="regular-price" id="product-price-1"><span class="price">€6.95</span></span>
</div>
</div>
<div class="table-top-qty">
<fieldset class="add-to-cart-box">
<input type="hidden" name="products[]" value="1"> <legend>Add Items to Cart</legend> <span class="qty-box"><label for="qty1">Qty:</label> <input name="qty1" disabled="disabled" value="0" type="text" class="input-text qty" id="qty1" maxlength="12"></span>
</fieldset>
</div>
<div class="table-top-details">
<input type="checkbox" name="buyMe" value="buy" class="add-checkbox">
</div>
<div style="clear:both;"></div>
</div>
here is the javascript i have tried
jQuery(document).ready(function() {
console.log('hello');
var thischeck;
jQuery(".table-products").ready(function(e) {
//var catTable = jQuery(this);
var qtyInput = jQuery(this).children('.input-text');
jQuery('.add-checkbox').click(function() {
console.log(jQuery(this).html());
thischeck = jQuery(this);
if (thischeck.is(':checked'))
{
jQuery(qtyInput).first().val('1');
jQuery(qtyInput).first().prop('disabled', false);
} else {
}
});
});
// Handler for .ready() called.
});
Not the most direct method, but this should work.
jQuery(document).ready(function() {
jQuery('.add-checkbox').on('click', function() {
jQuery(this)
.parents('.table-products')
.find('input.input-text')
.val('1')
.removeAttr('disabled');
});
});
use
jQuery('.add-checkbox').change(function() {
the problem is one the one hand that you observe click and not change, so use change rather as it really triggers after the state change
var qtyInput = jQuery(this).children('.input-text');
another thing is that the input is no direct child of .table-products
see this fiddle
jQuery('input:checkbox.add-checkbox').on('change', function() {
jQuery(this)
.parent()
.prev('div.table-top-qty')
.find('fieldset input:disabled.qty')
.val(this.checked | 0)
.attr('disabled', !this.checked);
});
This should get you started in the right direction. Based on jQuery 1.7.2 (I saw your prop call and am guessing that's what you're using).
$(document).ready(function() {
var thischeck;
$('.table-products').on('click', '.add-checkbox', function() {
var qtyInput = $(this).parents('.table-products').find('.input-text');
thischeck = $(this);
if (thischeck.prop('checked')) {
$(qtyInput).val('1').prop('disabled', false);
} else {
$(qtyInput).val('0').prop('disabled', true);
}
});
});
Removing the property for some reason tends to prevent it from being re-added. This works with multiple tables. For your conflict, just replace the $'s with jQuery.
Here's the fiddle: http://jsfiddle.net/KqtS7/5/