I'm trying to add restrictions on every duplicated field I add using jquery. The outcome should be that each duplicated field should restrict the user from entering more than 5 words per field.
This is the code I have so far. Anyone who can help? I'll appreciate it guys. Thank you!
$('.itextarea').each( function(){
$(this).on('keyup', function() {
var words = this.value.match(/\S+/g).length;
if (words > 5) {
var trimmed = $(this).val().split(/\s+/, 5).join(' ');
$(this).val(trimmed + ' ');
$('p.help').empty().append('You can only add 5 words per field.');
}else{
$('p.help').empty();
}
});
});
UPDATE: Sorry, here's the html for those who were asking for it.
<textarea class="itextarea form-control" name="id_desc[]" aria-required="true"></textarea>
When you want to share the same functionality on elements created by other scripts you can access them by using $('body').on( events, selectors, callback):
$('#add-field').on('click', function() {
$('#banner-message').append(`<input class="itextarea" />`);
})
// This is how you should access dynamically added elements
$('body').on('keyup', '.itextarea', function() {
var words = this.value.match(/\S+/g).length;
if (words > 5) {
var trimmed = $(this).val().split(/\s+/, 5).join(' ');
$(this).val(trimmed + ' ');
$('p.help').empty().append('You can only add 5 words per field.');
} else {
$('p.help').empty();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="banner-message">
<button type="button" id='add-field'>
Add New Field
</button>
<input class="itextarea" />
</div>
I created a sample fiddle for you. As mentioned by #darklightcode you should use such selector $('body').on( events, selectors, callback), but also you need to bind input event instead of keydown and also you need an additional check duplicated texarea fields. Hope this will help you
Related
var str1=$("#account-number").val().substring(0,4);
$("#first-four").html(str1);
I have tried multiple variations and attempts its been a few hours... so I thought I should ask for help...
I want to be able to take the first four characters of an input field with id "account-number" and send it to a div with id "first-four"
On thing to watch out for is change vs input. The first only fires when the input looses focus.
$("#account-number").on("input", function(){
$("#first-four").text(this.value.substring(0,4));
});
<input id="account-number" type="text" />
<div id="first-four"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$(document).ready(function(){
$("#account-number").blur(function(){
var accountNmbr = $("#account-number").val().substring(0,4);
$("#first-four").html(accountNmbr);
});
});
JSFiddle: https://jsfiddle.net/Lw4kr4Lq/
$( document ).ready(function() {
$( "#account-number" ).on("input", function() {
var str1 = $("#account-number").val().substring(0,4);
$("#first-four").html(str1);
});
})
I have this code
<span></span>
and this
<div> variable like a number </div>
and
<script>
$(document).ready(function(){
var x = $('div').html();
$('span').html(x)
});
</script>
I need that every time I change the div value, the span reflects the changes of the div
For example.
If I type 1 in the div, the span should immediately show me number 1
If I type 3283 in the div, the span should immediately show me number 3283
but with this code - I need to create
$("div").click(function(){
var x = $('div').html();
$('span').html(x)
});
I do not want to use .click(function) . in need this function run Automatically
after your answer
I use this code
http://jsfiddle.net/Danin_Na/uuo8yht1/3/
but doesn't work . whats the problem ?
This is very simple. If you add the contenteditable attribute to the div, you can use the keyup event:
var div = $('div'),
span = $('span');
span.html(div.html());
div.on('keyup', function() {
span.html(div.html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span></span>
<div contenteditable="true"> variable like a number </div>
here is a demo with input:
html:
<span></span>
<input type="text" id="input01">
js:
$(document).ready(function(){
$( "#input01" ).on('keyup',function() {
var x = parseFloat($('#input01').val());
$('span').html(x)
});
});
How can you edit in div element on browser?
It have to be any input type then only you can edit or change value.
So for that on click of that div you have to show some input/textarea at that place and on change event of that input you can update the value of input in span.
<div id="main-div">
<input type="text" id="input-box" />
</div>
<script>
$(document).ready(function(){
$('#input-box').change(function(){
$('span').html($(this).text)
});
});
</script>
$("input[type=text]").change(function(){
var x = $('div').html();
$('span').text(x)
});
This can be use with textbox or textarea, For div user cannot enter text.
http://jsfiddle.net/uuo8yht1/
.change() will not work with a DIV-element. Since you did not specify how the DIV is updated I would recommend either setting a timer or using .keypress()
Example with timer:
$(function(){
var oldVal = "";
var divEl = $("div");
setInterval(function(){
var elTxt = divEl.text();
if (elTxt != oldVal) {
oldVal = elTxt;
$("span").text(elTxt);
}
}, 50);
});
You need a key listener, jquery provides a .keypress(), Examples are provided on keypress documentation.
I recommend to lookup the combination of .on() and .keyup() with some delay or throttle/debounce either via jquery or underscore.js library.
One of the reason or need for delay is to prevent too many event calls which will affect performance.
Here is an example of code in another question regarding throttle and keyup
Hope this helps.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have my input Field and is using onKeyup and onKeyPress to return number & characters and then to move to the next field.
<input name="aendcodeM" id="aendcodeM" type="text" size="25" maxlength="4" onKeyPress="return numchar(event)" onKeyup="autotab(this, document.form1.bendcodeM)"/>
<input name="bendcodeM" id="bendcodeM" type="text" size="25" maxlength="4" onKeyPress="return numchar(event)" onKeyup="autotab(this, document.form1.bndwdM)"/>
I am trying to use feature of auto-capitalization also for which the code witten as -
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("input").keyup(function() {
var val = $(this).val()
$(this).val(val.toUpperCase())
})
})
</script>
<script>
$(document).ready(function() {
$("textarea").keyup(function() {
var val = $(this).val()
$(this).val(val.toUpperCase())
})
})
</script>
<script>
$(input[type="text"]).on('keypress', function() {
var $this = $(this), value = $this.val();
if (value.length === 1) {
$this.val( value.charAt(0).toUpperCase() );
}
});
</script>
But is of no use since the characters not getting automatically capitalized as desire. Any help in this regard is obliged please.
Thanks & Reagrds
Use css text-transform: uppercase for your input's text & textarea elements as:
input, textarea{
text-transform: uppercase;
}
This will work for you.
Many errors in your code:
why calling function when it isn't initialized?
Uncaught ReferenceError: autotab is not defined error in demo.
<input name="aendcodeM" id="aendcodeM" type="text" size="25" maxlength="4" onKeyPress="return numchar(event)" onKeyup="autotab(this, document.form1.bendcodeM)"/>
^^^^^ ^^^^
Here also ' is missing:
$('input[type="text"]').on('keypress', function() {
^ ^
Working DEMO
How to check Error in console
You should be using only one $(document).ready( ... ) in your Javascript.
Working demo of your code (fixed)
JS:
$(document).ready(function() {
$("input, textarea").keyup(function() {
var val = $(this).val()
$(this).val(val.toUpperCase());
});
$('input[type="text"]').on('keypress', function() {
var $this = $(this), value = $this.val();
if (value.length === 1) {
$this.val( value.charAt(0).toUpperCase() );
}
});
});
Check the demo
Jquery Code
$('[type=text]').keyup(function(){
if($(this).val()!=''){
$(this).val( $(this).val().toUpperCase());
}
});
Doing it that way is unnecessary. I strongly suggest you force uppercase by using the text-transform CSS property.
CSS
input{
text-transform: uppercase;
}
This will force clients to render text in uppercase at all times.
However
Be careful as the values are not. When you proccess your action it is important at that point you convert your value to uppercase either client side or server side.
try this
$( "#aendcodeM" ).bind( "input", function() {
$("#aendcodeM").val($("#aendcodeM").val().toUpperCase());
});
two things
You have to put semi-colon and also check if this is pointing properly
var val = $(this).val();//notice semicolon here
$(this).val(val.toUpperCase());//notice semicolon here
Here is your problem. You need to understand the concepts better. You are trying to register event handler both in javascript and jquery. autocad and numchar functions are not defined and since these are event handlers using javscript, when they get hit it wont work.
Find below the code and also check with this fiddle http://jsfiddle.net/wishy/qbfkhz88/
<input name="aendcodeM" id="aendcodeM" type="text" size="25" maxlength="4" />
<input name="bendcodeM" id="bendcodeM" type="text" size="25" maxlength="4" />
and javascript is
$(document).ready(function() {
$("input").keyup(function() {
var val = $(this).val();
$(this).val(val.toUpperCase());
});
});
$("textarea").keyup(function() {
var valtext = $(this).val()
$(this).val(valtext.toUpperCase())
});
Demo
The above code is works on all the textarea of the page.Firstly we will take take the value of textarea where user is start typing then make it Upper case using inbuilt function of jquery and assign to the textarea.
Sometimes i found that when you use variable name same as function name or same as any keyword, then it throws error
so try to do one thing. Also use ids.
$(document).ready(function() {
$("#text_area").keyup(function() {
var valtext = $(this).val()
$(this).val(valtext.toUpperCase())
})
})
Just have a test with this. May be this is the scenario happening on your case
Also use ids.
see the fiddle http://jsfiddle.net/36bqfms6/
To be as simple as I can:
I have condition where I do not know where I'm going to have 3 or more input elements (type of "text") and I'm looking for solution which will generate 4th input type text when I start to fill 3th input field with characters, and so on.
Something similar Adminer have for adding new columns when creating/altering database:
here you click on + to add new input and x to remove it. This would also be good to me.
How to achieve that/what library should I use?
You can clone full row, and append it to parent table. Have a look at jQuery clone() and append().
Sample code:
$('#yourtableid').on('click', '.add', function() {
// clone first row
var row = $('#yourtableid tbody tr:first').clone();
// reset inputs
row.find('input[type!=button]').val('');
// append cloned row
$('#yourtableid tbody').append(row);
});
Live DEMO.
EDIT: To add row automatically when filled some text in last row, you can go with:
$('#tbl').on('change', 'input', function() {
// check that some input was entered and that it is in the last tr
if($(this).val() != '' &&
$(this).closest('tr').is(':last-child')) {
addRow();
}
});
It's difficult to tell what you're trying to get without a code sample, but do you want something like this?
HTML:
<input type='text' />
JS:
$('input').on( 'change', function() {
$(this).after( '<input type="text" />' );
$('input').off( 'change' );
});
jsFiddle is down and jsBin can't handle the extra load, but here's a demo.
This code loads via jQuery a page based onclick events of checkboxes.
function product_analysis(address, box) {
if (box.checked) {
$('#product_' + box.alt).load(address);
} else {
$('#product_' + box.alt).load('http://www.divethegap.com/update/blank2.html');
}
document.getElementById('product_quantity_PRI_' + box.alt).value = box.value;
};
With the onclick event looking as follows onclick="product_analysis('http://www.samedomain.blahblahblah', this)
What I need is that for all checkboxes that are already ticked on page load to have this function applied to them all. I am reasonably confident with javaScript but when it comes to objects and arrays I get lost.
Many Thanks,
You can use this code to find all the checkboxes that are currently checked:
$(':checkbox:checked')
If you then want to do something to all of them, you can use the each function like this:
$(':checkbox:checked').each(function() {
// alerts the checkbox for example
// "this" referes to the checkbox, one after the other
alert(this);
})
Or to do what you asked for ("for all checkboxes that are already ticked on page load to have this function applied to them all"):
$(':checkbox:checked').each(function() {
product_analysis("someaddress", this);
})
EDIT: To address the second issue (not a part of the original question, but to the comments below):
I will assume that you have fields like this in your markup. Use some meaningful IDs rather than my stupid examples of course.
<input type="checkbox" id="foo" />
<input type="checkbox" id="bar" />
<input type="checkbox" id="baz" />
Then you'll put the following in your JS:
var addresses = {
foo: 'some_address',
bar: 'some_other_address',
baz: 'yet_another_one'
};
$(':checkbox:checked').each(function() {
product_analysis(addresses[this.id], this);
})
That will invoke product_analysis with the address that corresponds to the ID of the checkbox.
EDIT (again):
There is actually a way to add meta-data directly to the html-tags that I wasn't aware of. You can add attributes prefixed by "data-" to your tag, like this:
<input type="checkbox" data-address="someaddress" data-foo="something else" data-bar="more data!" />
You can read more about it on John Resigs blog.
this is required script
$().ready(function(){
var box, address;
$(":checkbox").each(function(){
box = this;
if (box.checked) {
address = ""; //you can set address either in hidden fields or in metadata
$('#product_' + box.alt).load(address);
}
else {
$('#product_' + box.alt).load('http://www.divethegap.com/update/blank2.html');
}
document.getElementById('product_quantity_PRI_' + box.alt).value = box.value;
});
});
You need to check how many number of check is checked and then invoke your code.
var checkLength = checkObj.length;
for(var i = 0; i < checkLength ; i++) {
if(radioObj[i].checked) {
}
// here your code base on check box status
}
If you have a class called as "selected" when the check box are checked, you could do something like this
$('.selected').function(element){product_analysis(address, element)};
Thanks chaps for all your help here is I I got it. Jakob will probably consider this a hack but it is a data driven site and based on my limited technical knowledge can't be tasked with modifying a JS file every time we add a new product.
function product_analysis_global() {
$(':checkbox:checked').each(function() {
$('#product_' + this.alt).load(this.title);
});
}
function product_analysis(box) {
if (box.checked) {
$('#product_' + box.alt).load(box.title);
}
else {
$('#product_' + box.alt).load('http://www.divethegap.com/update/blank2.html');
}
document.getElementById('product_quantity_PRI_' + box.alt).value = box.value;
};