I want to append various things to an input with buttons.
button#addNumber -> appends 245
button#addOperation -> appends +
A problem arises with button#radicSign.
I want to add the template for a square root sqrt() and place the caret inside the parentheses afterwards for the user to type in the number.
Is this possible?`
If yes, is it worth the effort? Or should I open a dialog box and insert it then?
$('button#radicSign').on('click', function add2digit() {
addOperation('sqrt');
});
function addOperation(op) {
var problemInput = $('input#testProblem');
problemInput.val(problemInput.val() + op);
}
You should be able to do something like this to achieve what you want:
$('#sqrt').click(function() {
var length = $('#a').val().length;
$('#a').val($('#a').val()+'sqrt()');
$('#a').focus()[0].setSelectionRange(length+5, length+5);
});
JSFiddle
Related
I have a bunch of divs with matching ids (#idA_1 and #idB_1, #idA_2 and #idB_2, etc). In jquery I wanted to assign click functions, so that when I click an #idA it will show and hide an #idB.
Basically I want to make this:
$(".idA_x").click(function(){
$("idB_x").toggleClass("hide")
});
X would be a variable to make #idA and #idB match. I could write each individually, but that would take too much code, is there a way to make the number in the id into a variable?
Sure, you can do:
var num = 13;
addButtonListener(num);
function addButtonListener(num){
$("#idA_"+num).click(function(){
$("#idB_"+num).toggleClass("hide")
});
}
Try JQuery solution :
var x = 1;
$(".idA_" + x ).click(function(){
$(".idB_" + x ).toggleClass("hide")
});
Hope this helps.
There are many ways to achieve that, but what you probably want is to create a shared CSS class, e.g. .ids, and bind the event listener to that one:
$('.ids').click(function () {
//...
});
Then you can handle your logic in a cleaner way within the function body.
In order to make it dynamic, and not have to repeat the code for each one of your numbers, I suggest doing as follows:
First, add a class to all the div's you want to be clickable .clickable, and then use the id of the clicked event, replacing A with B in order to select the element you what to toggle the class:
$(".clickable").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
Or, you can also select all divs and use the contains wildcard:
$("div[id*='idA_']").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
This solution won't have the need to add a class to all clickable divs.
You can use attribute selector begins with to target the id's you want that have corresponding elements.
https://api.jquery.com/attribute-starts-with-selector/
Then get the value after the understore using split on the id and applying Array.pop() to remove the 1st part of the array.
http://jsfiddle.net/up9h0903/
$("[id^='idA_']").click(function () {
var num = this.id.split("_").pop();
$("#idB_" + num).toggleClass("hide")
});
Using regex would be your other option to strip the number from the id.
http://jsfiddle.net/up9h0903/1/
$("[id^='idA_']").click(function () {
var num = this.id.match(/\d+/g);
$("#idB_" + num).toggleClass("hide")
});
Suppose I have a div that contains a sentence such as the one listed below:
<div class="sentence">This is a sentence</div>
I am trying to create a function/event handler that will recognize when the user clicks on the text inside the <div>. But, when they click inside the <div> the function needs to know exactly where they clicked so I can insert a <span> at that location. For example, if the user clicks in between the letters 'n' and 't' in the word 'sentence', then I want to insert a <span> there so I end up with
<div class="sentence">This is a sen<span>test</span>tence</div>
Something like this:
$('.sentence').on('click', function (e) {
var to_insert = '<span>test</span>';
// determine exactly where inside the div I clicked
// insert 'to_insert' at that location
});
Any ideas?
You can to get the position of the click in a string, using window.getSelection().anchorOffset
JS
$('.sentence').on('click', function (e) {
var to_insert = 'test';
var anchorOffset = window.getSelection().anchorOffset;
var resultHtml = $(this).html().substring(0, anchorOffset) + to_insert + $(this).html().substring(anchorOffset);
$(this).html(resultHtml);
});
DEMO
I'm using a text box like the following and I want that the text box width will be according to the size of the text inside, it that possible?
#Html.TextBoxFor(model => model.Name, new { disabled = "disabled" })
An easy answer for your problem is(using some jquery):
<script>
$(document).ready(function () {
$('.txt').css('width', (($('.txt').val().length)+1) * 7 + 'px'); //You can increase or decrease multiplication factor i.e '7' here as required.
});
</script>
#Html.TextBoxFor(model => model.Name, new { disabled = "disabled",#class="txt" })
DEMO Link :- http://jsfiddle.net/Lbaf8cek/5/
Not for this question because here textbox is disabled but if textbox is not disabled then most easiest way to adjust textbox width is :
<input id="txt" type="text" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';">
Fiddle Link :-http://jsfiddle.net/kartikeya/1vnw7d44/
UPDATED WITH CODE EXPLANATION:
here you go, the input will always be as long as its characters, whether you type, remove or give it a value before running the script: DEMO
//this is a plugin snippet (or function) to check if the element has
//horizontal scrollbar
$.fn.hasHorizontalScrollBar = function() {
if (this[0].clientWidth < this[0].scrollWidth) {
return true
} else {
return false
}
}
//the end of plugin
var originalWidth=$('.txt').width(); //we store the original width
//(the width of the input at the page load) in a variable to use it as a
//measurement in order to not let the input get smaller than this size
//this function checks the width of `.txt` (the input) to see if it has
//horizontal scrollbar or not, if it does then expands the width of the input to
//the scroll size, else it checks to see if the width is added to the
//original width, if so, removes one character (depending on the font size it'll
//change - here it is 7 px)
function changeWidth(){
if($('.txt').hasHorizontalScrollBar()){
$('.txt').width(document.getElementsByClassName('txt')[0].scrollWidth);
}
else if(originalWidth<$('.txt').width()){
$('.txt').width($('.txt').width()-7);
}
};
//end of the function
changeWidth(); //run the function at page load, to give the input a size as wide as its
// character's length
$('.txt').keydown(changeWidth); //assign the function to the keydown event of the input
//so whenever a character is added or removed the function will run again
This post handles the same topic I believe: Growing text box based on width of characters input
Since you're using mvc and the textbox is disabled for edits, you could try:
#Html.TextBoxFor(model => model.Name, new { disabled = "disabled", length = Model.Name.Length() })
Sorry if my syntax is incorrect but I don't have an IDE up atm. But what you're doing is setting the textbox length to the number of characters of the input. This should effectively set the textbox to the correct length. Unless you have some css rules applied somewhere.
UPDATE:
Another way (like below) is by using Javascript, this way you can widen or shorten your textbox dynamically based on input. But preferably, when it's only for displaying the name, you should try #Html.DisplayFor(...)
Putting together a very basic query builder using or, not and () operators. I have them appending to an input field though I think it would be beneficial to the user if when the brackets operator button was appended to the input field the cursor would be placed (here) ready for the users query.
So far I have:
// query builder functions
$(function() {
var queryinput = $( "#query-builder-modal .search-box input.querybuilder" );
$('#query-builder-modal ul.operators li.or').click(function(){
queryinput.val( queryinput.val() + "OR" );
queryinput.focus();
});
$('#query-builder-modal ul.operators li.not').click(function(){
queryinput.val( queryinput.val() + "-" );
queryinput.focus();
});
$('#query-builder-modal ul.operators li.brackets').click(function(){
queryinput.val( queryinput.val() + "()" );
queryinput.focus();
});
});
Can anyone help me plave the cursor between the brackets in the third click function of this sample code?
Thanks in advance
You can try something like this :
$('#query-builder-modal ul.operators li.brackets').click(function(){
queryinput.val( queryinput.val() + "()" );
var pos = queryinput.val().length - 1;
myInput.focus(); /* Seems mandatory for Firefox/Opera */
queryinput[0].selectionStart = queryinput[0].selectionEnd = pos;
});
jsfiddle example here
EDIT: It seems that for Firefox and Opera, you must first focus() your input but not on Safari and chrome. I updated the code and the jsfiddle.
I have dynamically added div.In which i have text box.While adding dynamic div i can put a value to the current div but not the previously open divs. I want to ask how to add Value to the previously open text boxes of Div.
Thank You
here is a solution that refresh ALL. (I don't understand the "previously open text box" part of your question. Well I understand it, but it doesn't show in your code. I assume the "rhythm" column of your table is an input/textarea html element (since you use it's value).
Please note I'm not sure what the vitalset function is supposed to accomplish, or what "vitals_form_readings_1_rhythm" is.
function queryDb(statement)
{
dbQuery = new air.SQLStatement();
dbQuery.sqlConnection = db;
dbQuery.text = statement //"SELECT * FROM rhythm";
//alert(dbQuery.text);
try {
dbQuery.execute();
} catch (error) {
air.trace("Error retrieving notes from DB:", error);
air.trace(error.message);
return;
}
return (dbQuery.getResult());
}
function crhythm()
{
var statement = "SELECT * FROM rhythm";
return queryDb(statement)
}
function reading_speedcode()
{
if (!cvitals) {
var crhythms = crhythm();
var i=0;
$(crhythms).each( function () {
crhythm = this.crhythm;
var pr = 'card_' + i;
$('#rhythm1').append('<br/><td class="content_big" id="'+pr+'" name="'+pr+'">' + crhythm + ' </td>');
i++
});
}
});
$(document).ready( function () {
reading_speedcode();
$('#rhythm1 .content_big').live('click', function(event) {
$('#rhythm1').empty()
reading_speedcode();
});
});
now, there are several things about your code.
variable naming. (for god sake use meaningful names!)
reading full table when you need one row
where is cvitals declared or assigned?
string parsing. Jquery is good at working with set of elements, there should be no need to parse "pr" to recover the row number.
if a value is inserted in rhythm table (or deleted) before your click, the vitalset logic fails. you might want to use the table id instead.
make sure "#vitals_form_readings_1_rhythm" is unique, not retrieved from the table.
if you can answer my question from the top of this post(vitalset function, vitals_form_readings_1_rhythm, cvitals) I will try improve the code.