function in javascript not working when called - javascript

I have a javascript code that works by removing the first and the last line of it.
Please take a look at JSFiddle
for people who wants to see it in here, here is my html:
<input id="search" onclick="search()" type="button" value="Search"/>
my javascript :
function search() {
var search = document.getElementById('search');
var int = setInterval(function() {
if (search.value.length == 6)
search.value = 'Searchi';
else if (search.value.length == 7)
search.value = 'Searchin';
else if (search.value.length == 8)
search.value = 'Searching';
else {
search.value= 'Search';
}
//clearInterval( int ); // at some point, clear the setInterval
}, 500);
}
I want the function to work only when I click the button.

You've selected jQuery in jsfiddle.net which by default causes the site to wrap your whole code in a document.ready handler.
The result is that your search function becomes a local function within that wrapper, and not a global variable as required by a DOM0 onclick handler.
Set the jsfiddle options to "no wrap (body)" and "No-Library (pure js)" to turn off that functionality.

Related

How to match anything between < & > in regex?

I'm trying to match anything that lies between < and >, and nothing seems to be working.
My current code is:
var regex = /\<(.*?)\>/
var targeting = $('#auto-expand').val //A text area
function validateText(field)
{
if (regex.test(field) == true)
{
alert(field.match(regex))
}
else
{
alert("fail")
}
}
It keeps returning fail, not sure why.
Any help would be so great! :)
It's not clear from your question how you are calling the validateText function. But it looks like are trying to set targeting outside the function, which means you are probably setting it before there's text in the box.
Below I change val to val() to call the function and looked up the value when the function runs rather than before. The regex itself works fine (keeping this in mind)
var regex = /<(.*?)>/
function validateText() {
var targeting = $('#auto-expand').val() //A text area
if (regex.test(targeting) == true) {
alert(targeting.match(regex))
} else {
alert("fail")
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="auto-expand"></textarea>
<button onclick=validateText()>Test</button>

Passing an element into a javascript function which is then added to EventListener

I am trying to write a small javascript to validate the input of type = "number" in the form of my website. Basically, this function is trying to make sure the maximum length of input allowed is no longer than the arguments I have passed in. I wrote the function to take in two arguments, one is an html element and the other is the maxlength. However, after I add this function to the input element, it does not seem to be working. Please take a look and tell me where I have gone wrong and what concepts I missed.
/* Show submit button only when the form has been validated */
/* Variables */
var form = document.querySelector(".resForm");
var resFormBtn = document.querySelector(".submitButton");
var numInput = document.querySelector("#numberInput");
function showSubmitButton() {
if (form.checkValidity() === true) {
resFormBtn.style.display = "block";
}
}
function validateNumInput(maxlength, ele) {
if (ele.length > maxlength) {
ele.value = ele.value.slice(0, maxlength);
}
}
form.addEventListener("change", showSubmitButton, false);
numInput.addEventListener("input", function () {
validateNumInput(8, numInput);
}, false);
if (ele.length > maxlength)
There is something wrong here. ele is a referenced node, it has no such a property called "length", therefore the code inside the condition will never trigger.
simply change it to
ele.value.length > maxlength
the code will just do fine

bind javascript function to input control on window load

I amm develloping an web form with multiple text box with same css class.
and i want to bind a specific method to all these textboxes who use that class.
belows are my codes
window.onload = function ()
{
var tObj = document.getElementsByClassName('exa');
for (var i = 0; i < tObj.length; i++) {
tObj[i].onblur(convertAmount(event,this));
}
}
the another function 'convertAmount()' is below
function convertAmount(evt, obj) {
if (obj.value != "") {
var num = parseFloat(obj.value);
num = Math.round((num + 0.00001) * 100) / 100;
obj.value = num.toFixed(2);
}
else {
obj.value = "0.00";
}
}
html codes
<div>
<input type="text" id="finalvalue" class="exa"/>
<input type="text" id="grossvalue" class="exa"/>
<div>
when browser load first time only '0.00' values are coming on those text boxes. but when i type some values on those text boxes and press tab its not working! please help what is wrong here
As commented before, you should assign a eventHandler and not pass it as callback.
So you code would be:
tObj[i].onblur = convertAmount.bind(this, event, this);
Also, event is default argument for any eventListener and current object/element is automatically binded to it, so above code can be simplified to
tObj[i].onblur = convertAmount;
This will bind the context and you will get all properties in this.
Sample Fiddle
Note: you should use addEventListener instead. onBlur = will replace all previous events. addEventListener will add another one.
Sample Fiddle
I hope this link helpful to you.
<div>
<input type="text" id="finalvalue" class="exa"/>
<input type="text" id="grossvalue" class="exa"/>
<div>
$(document).ready(function(){
$('.exa').each(function(index,value){
$(this).attr('onblur',convertAmount(event,$(this)))
})
})
function convertAmount(evt, obj) {
if (obj != "") {
$(obj).val('0.00')
}
else {
$(obj).val('0.00')
}
}

Button Text Does Not Change jQuery

Okay, I have been messing around with this for a few hours now and decided to ask. I have searched StackOverflow and Google, with no resolution. I am trying to change the text of a button, like below.
<input id="btnRegUpdate" type="submit" onclick="updatePrice(1)" value="Correct">
The updatePrice() function is called and checks a few things and at the end I have an if statement that checks the value to see if it is Correct, if it is, it will change the text, or suppose to.
var btnRegUpdate = $('#btnRegUpdate');
if (btnRegUpdate.attr('value') == 'Correct'){
logMessage("Button was correct");
btnRegUpdate.text("Update");
}
At this point I have tried everything in this solution jQuery change button text with nothing working. I get the logMessage, but the button still doesn't change.
UPDATE: Nothing seems to be working. I tried everything again in a new function, just in case the other logic was messing with something. After doing a quick test to see if the text was change
function updatePrice2(val, e) {
e.preventDefault();
var btnRegUpdate = $('#btnRegUpdate');
if (btnRegUpdate.attr('value') == 'Correct') {
logMessage("Button was correct");
btnRegUpdate.val("Update");
}else if(btnRegUpdate.attr('value') == 'Update'){
logMessage('Button was update');
btnRegUpdate.val("Correct");
}
}
and the console shows that it changed but doesn't on screen.
Change the innerHTML not the text. Like so:
btnRegUpdate.html("Update");
EDIT:
Just noticed you're using a <input> not a <button>, change the value property:
btnRegUpdate.attr('value', 'Update');
You need
btnRegUpdate.attr("value", "Update")
instead of
btnRegUpdate.text("Update");
var btnRegUpdate = $('#btnRegUpdate');
if (btnRegUpdate.val() == 'Correct'){
btnRegUpdate.attr('Value',"Update");
}
Try using btnRegUpdate.attr('Value',"Update");
Demo
Try this:
Prevent default action of submit button
Change the value of button using val()
function updatePrice(val, e) {
e.preventDefault();
var btnRegUpdate = $('#btnRegUpdate');
if (btnRegUpdate.attr('value') == 'Correct') {
console.log("Button was correct");
btnRegUpdate.val("Update");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="btnRegUpdate" type="submit" onclick="updatePrice(1,event)" value="Correct">
The input element's text is defined by its value attribute, not content. To change the text, update the value attribute:
btnRegUpdate.attr('value', "Update");
instead of
btnRegUpdate.text("Update");
With jQuery you can use .html() to change the contents. It works the same as javascript's .innerHtml
var btnRegUpdate = $('#btnRegUpdate');
if (btnRegUpdate.attr('value') == 'Correct'){
logMessage("Button was correct");
btnRegUpdate.html('Update')
}
Add return false to the click handler.
<input id="btnRegUpdate" type="submit" onclick="updatePrice(1); return false;" value="Correct">
Otherwise the page will attempt to submit and reload.
Your function look good and i don't know it's not working.
function updatePrice2(val, e) {
e.preventDefault();
var btnRegUpdate = $('#btnRegUpdate');
if (btnRegUpdate.attr('value') == 'Correct') {
logMessage("Button was correct");
btnRegUpdate.val("Update");
}else if(btnRegUpdate.attr('value') == 'Update'){
logMessage('Button was update');
btnRegUpdate.val("Correct");
}
}
I suggest you check in your page and find id "btnRegUpdate", maybe it appear more than one.

Detect programmatical changes on a html select box

Is there a way to make a HTML select element call a function each time its selection has been changed programmatically?
Both IE and FF won't fire 'onchange' when the current selection in a select box is modified with javascript. Beside, the js function wich changes the selection is part of framework so I can't change it to trigger an onchange() at then end for example.
Here's an example:
<body>
<p>
<select id="sel1" onchange="myfunction();"><option value="v1">n1</option></select>
<input type="button" onclick="test();" value="Add an option and select it." />
</p>
<script type="text/javascript">
var inc = 1;
var sel = document.getElementById('sel1');
function test() {
inc++;
var o = new Option('n'+inc, inc);
sel.options[sel.options.length] = o;
o.selected = true;
sel.selectedIndex = sel.options.length - 1;
}
function myfunction() {
document.title += '[CHANGED]';
}
</script>
</body>
Is there any way to make test() call myfunction() without changing test() (or adding an event on the button)?
Thanks.
If you can extend/modify the framework to give a hook/callback when they change the select options, it would be better (one way could be to use the dynamic capabilities of js to duck type it in?).
Failing that, there is an inefficient solution - polling. You could set up a setTimeout/setInteval call that polls the desired select option dom element, and fire off your own callback when it detects that something has changed.
as for the answer to your question
Is there any way to make test() call
myfunction() without changing test()
(or adding an event on the button)?
yes, by using jquery AOP http://plugins.jquery.com/project/AOP , it gives an easy-ish solution.
<body>
<p>
<select id="sel1" onchange="myfunction();"><option value="v1">n1</option></select>
<input type="button" onclick="test();" value="Add an option and select it." />
</p>
<script type="text/javascript">
var inc = 1;
var sel = document.getElementById('sel1');
function test() {
inc++;
var o = new Option('n'+inc, inc);
sel.options[sel.options.length] = o;
o.selected = true;
sel.selectedIndex = sel.options.length - 1;
}
function myfunction() {
document.title += '[CHANGED]';
}
//change to aop.after if you want to call afterwards
jQuery.aop.before( {target: window, method: 'test'},
function() {
myfunctino();
}
);
</script>
</body>
Define your own change function that calls the framework function and then calls a
callback function.
e.g.:
function change(callback)
{
frameworkchange();
callback();
}
The answer is .... no.
The DOM only fires the onchange event as a result of user action not code. It does not provide any additional events to hook in this regard.
You will need to customise the framework or drop your requirement.
ahem...
you can access the event 'onpropertychange' it contains a property within the event arguments to identify which property was changed.
It detects both 'selectedIndex' and 'value' changes - simply case test 'propertyName' I'm currently working with the ASP.NET js framework here is some straight copy-paste code for that:
1) define handler:
this._selectionChangedHandler = null;
2) assign handler
this._selectionChangedHandler = Function.createDelegate(this, this._onSelectionChanged);
3) attach handler to event
$addHandler(element, "propertychange", this._selectionChangedHandler);
4) create function
_onSelectionChanged: function(ev) {
if (ev.rawEvent.propertyName == "selectedIndex")
alert('selection changed');
},
With JQuery, you could do something like
$(document).ready(function(){
$('#select-id').change(function(e){
e.preventDefault();
//get the value of the option selected using 'this'
var option_val = $(this).val();
if(option_val == "v1"){
//run your function here
}
return true;
});
});
This would detect the change programmatically and let you respond to each item changed

Categories