add selected radio value to search keyword on buttonclick - javascript

In my page I have two radios, user may select any one and type their search word in the input box, on button click I would like to append to their search keyword the value of selected radio?How do we do that in jquery or javascript?
So if they typed in Dance and selcted 'classes' the actual search keyword being passed will be 'Dance classes'
<div>
Events<input name="EventRadio" type="radio" value="Events"/>
Classes<input name="EventRadio" type="radio" value="Classes"/><br /><br />
<input type="text" name="T1" style="width: 302px"/>
<input type="button" value="Search" onclick="javascript:_SFSUBMIT_"/>
</div>

Need some more information: are you wanting the additional keyword to be displayed in the text box as well?
All you really need to do is capture the value attr of the radio if checked in your SFSUBMIT function. jQuery has several different constructs to do this.

If I'm understanding the question, when the user clicks the button, append what's in the textbox with the radio button currently checked?
$("input[type='button']").click(function() {
var text = $("input[name='EventRadio']:checked").val();
if (text) {
var $tb = $("input[name='T1']");
$tb.val($tb.val() + text);
}
});
Of course this will fire for all buttons - naturally you can add an id to this particular button an narrow the selector
$("#buttonId").click(function() {

$( "button" ).live(
'click',
function ( )
{
$strVal = $( "[name='T1']" ).val( ) . $( "[name='EventRadio']:checked" ).val( );
$( "[name='T1']" ).val( $strVal );
}
);

$('input[type="button"]').on('click', function () {
var $this = $(this),
concocted = $this.prev().val() + ' ' + $this.prevAll('[type="radio"]:checked').val();
//you can now do what you want with the `concocted` variable, which is in the format "{text-input} {radio input}"
});
Here is a demo: http://jsfiddle.net/LAuZW/
Note that this code will work if you have more than one set of inputs since all the selectors are based off this which is the clicked button input.
Also note that .on() is new in jQuery 1.7 and in this use-case is the same as .bind().

Related

Jquery get attribute ID for latest click

im trying to get the attribute value through jquery
$(document).click(function() {
var elem = $("input[name='phone']");
alert(elem.length);
if(elem.length > 0){
alert(elem.attr('id'));
}
});
here the case is
i have lots of input fields with same name as "phone" in different form. Whenever i click it i can get only the first value. Not the last one. How can i get it through the Jquery.
In my page only document click will work because the form codes are loading from some other site.
Any help is more appreciate
$( "input[name^='phone']" ).last()
will return the last element with name beginning with 'phone'
You can do this, to get the id of the item that is clicked.
$("input[name='phone']").click(function() {
alert($(this).attr('id'));
}
This is attaching the listener to phone inputs and this is the context, which in this case the item that is clicked.
Try this:
$("input[name='phone']").on('focus', function(){
alert($(this).attr('id'));
}
This will listen to clicks on your phone input fields and alert the id attribute for you to see on screen:
JQuery
$("input[name='phone']").click(function() {
alert($(this).attr("id"));
});
HTML example
<input id="a" name="phone">A</input>
<input id="b" name="phone">B</input>
<input id="c" name="phone">C</input>
<input id="d" name="phone">D</input>
Delegate the event with .on(), then you can use this:
$(document).on('click', 'input[name="phone"]', function() {
console.log('element with id: ' + this.id + ' has value: ' + this.value);
});

Keyup event fires on document load

jsfiddle
http://jsfiddle.net/m3g6rjok/1/
html
<textarea id="feedback" rows="4" cols="50" name="comment" maxlength="50">Enter text here...</textarea>
<br>
<input type="text" value="10" id="lenbox"></input>
js
$(document).ready(function(){
$( "#feedback" )
.keyup(function() {
var value = $( this ).val();
alert(value)
$( "#lenbox" ).val( value );
})
.keyup();
})
I need to calculate the number of words thats entered on the textarea and need to display it on the text box below..I'm using the keyup event to check but it gets triggered even on the page load. How can I fix it
Remove the .keyup(); from your code. This triggers the keyup event on page load.
The keyup event is raised because you trigger one. Remove the .keyup() after your handler function declaration:
$("#feedback").keyup(function() {
var value = $(this).val();
alert(value)
$("#lenbox").val(value);
})
Because you have .keyup(); at the end of your JQuery statement.
Just remove it
You should not trigger the keyUp again. Also, you should move the code that's updating the value outside of the keyUp function, so you can also trigger the code on page load. After you've done that, it's just taking a string, split on spaces and count the words:
var calculateCount = function() {
var value = $('#feedback').val();
var count = value.split(" ").length;
$( "#lenbox" ).val( count );
};
$(document).ready(function(){
$("#feedback").keyup(calculateCount);
calculateCount();
})
http://jsfiddle.net/qd6aznwa/
DEMO
First, Remove .keyup() as has been pointed out already
Then, use input instead of keyup so that I can also catch pasted text.
Finally, count the number of words by using the split method and the length property.
$(document).ready(function(){
$( "#feedback" ).on('input',function() {
$( "#lenbox" ).val( this.value.split(' ').length );
});
});
If you dont mind using HTML5 use the placeholder property
<textarea id="feedback" rows="4" cols="50" name="comment" maxlength="50" placeholder="Enter text here..."></textarea>

Id Starwith and .not() selector

I have done a validation to avoid special characters with the following code for all input text, however, I have input text that require having special characters. My code is as follows
$('.twTextinput input, .twTextinput textarea').not( $( '#txtEmailPersonal input, #txtEmailTrabajo input' )).keyup(function (){
this.value = this.value.replace(/[^a-zA-Z0-9 _]/g,'');
});
The problem is this, I have an input text that must be within the selector .not(). Is a input text that has an id that starts with "iccw". I tried with this code but does not work
$('.twTextinput input, .twTextinput textarea').not( $( '#txtEmailPersonal input, #txtEmailTrabajo input, input[id^="iccw"]' )).keyup(function (){
this.value = this.value.replace(/[^a-zA-Z0-9 _]/g,'');
});
Any suggestions.
Thanks in advance.
That is an awfully complex way single out one special input, don't you think?
I would tend to want find all "regular" textareas or inputs into an container and use find to collect them, and then single out the other "normal" inputs.
$normal_input_list = $(container).find( 'input.normal, textarea.normal' );
$special_input_list = $( '#icww' );
onKeyupNormal = function (){
this.value = this.value.replace(/[^a-zA-Z0-9 _]/g,'');
};
// and now bind the handler
$normal_input_list.on( 'keyup', onKeyupNormal );
If there is a good reason to select as you have, then I have determined the following should work:
$('input, textarea').not( '#wmd-input' );
Specifying input and ID is redundant, as ID is already unique across the page.
Hope that helps!
Here's a hack:
$('.twTextinput input, .twTextinput textarea').not( $( '#txtEmailPersonal input, #txtEmailTrabajo input'
)).keyup(function (){
if( this.id != 'iccw' ) {
this.value = this.value.replace(/[^a-zA-Z0-9 _]/g,'');
}
});
I would tend to control this with HTML attributes. I find it more manageable.
<textarea data-allowedchars="[^a-zA-Z0-9 _]"><textarea>
<textarea ></textarea>
<input data-allowedchars="[^a-zA-Z0-9 _]" />
<input />
JS
$("body").on("keyup", "[data-allowedchars]",
function(e){
var $t = $(this),
re = new RegExp($t.data("allowedchars"),'g');
$t.val($t.val().replace(re, ""));
}
);
Sorry this doesn't directly answer your question. It is hard to see what is wrong with your syntax without seeing the code.

JQuery focus to previous clicked input bug

I have two input fields. The main idea is that whenever you focus to one of the fields, the button click should print a random number inside it.
My problem is that when you just focus on (click on) the first field, then focus on second (or vice versa), the button click prints to both instead of just to the (last) focused field.
You can try to recreate the problem here: http://jsfiddle.net/sQd8t/3/
JS:
$('.family').focus(function(){
var iD = $(this).attr('id');
$("#sets").one('click',function() {
var ra = Math.floor((Math.random()*10)+1);
$('#'+iD).val(ra);
});
});
HTML:
<center class='mid'>
<input type="text" class="family" id="father" />
<br/><br>
<input type="text" class="family" id="mother" />
<br/>
<br/>
<input type='submit' value='Set text' id="sets"/>
</center>
In the "focus" handler, unbind any existing "click" handler:
$('#sets').unbind('click').one('click', function() { ... });
The way you had it, an additional one-shot "click" handler is bound each time a field gets focus, because jQuery lets you bind as many handlers as you like to an event. In other words, calling .one() does not unbind other handlers. When the click actually happens, all handlers are run.
edit — sorry - "unbind" is the old API; now .off() is preferred.
Put the variable iD outside, and separate the functions:
http://jsfiddle.net/sQd8t/8/
This prevents from adding too many events on each input click/focus.
No need to unbind.
var iD;
$('.family').focus(function() {
iD = $(this).attr('id');
});
$("#sets").on('click', function() {
var ra = Math.floor((Math.random() * 10) + 1);
if (iD!="")$('#' + iD).val(ra);
iD = "";
});
See http://jsfiddle.net/sQd8t/11/
$('.family').focus(function(){
$("#sets").attr('data-target',$(this).attr('id'))
});
$("#sets").click(function() {
var target=$(this).attr('data-target');
if(target){
var ra = Math.floor((Math.random()*10)+1);
$('#'+target).val(ra);
}
});
You can create a data-target attribute which contains the field which must be modified.

Knowing the last clicked textbox via Javascript

I have a form and a button.
I need that when I click on a textfield, and then click this particular button, the textbox which was clicked last will change its value to say "BUTTON HAS BEEN CLICKED".
Is there a way via JavaScript how I can know the last textbox which was clicked?
Many thanks in advance.
You need to store a reference to the text box when you click it. The easiest way to do that is to create a global variable for the reference. Then you would update the reference with the textbox's onclick event. Here is an example:
HTML:
<input id="myTextBox" type="text" onclick="updateCurText(this);">
<input type="button" value="click me" onclick="updateText();">
JavaScript:
var currentTextBox = '';
function updateCurText(ele) {
currentTextBox = ele.id;
}
function updateText() {
document.getElementById(currentTextBox).value = 'BUTTON HAS BEEN CLICKED';
}
Live example.
jsumners is correct, however I would probably recommend avoiding global variables, and if you're using something like jQuery you have encapsulate a lot of the logic in a single file:
$(function() {
var lastBox = false, formSelector = "form.myClass";
// Change events
$(formSelector + " input[type='text']").click(function() {
lastBox = this;
});
// Button click
$(formSelector + " button").click(function() {
if (lastBox)
$(lastBox).val("BUTTON HAS BEEN CLICKED");
});
});
live

Categories