So basically here is my jsFiddle - http://jsfiddle.net/CmNFu/ .
And code also here -
HTML -
<b style="float: left; margin-right: 10px;">category 1</b><input type="checkbox" value="category1" style="float: left;" class="portfolio-category" /><br />
<b style="float: left; margin-right: 10px;">category 2</b><input type="checkbox" value="category2" style="float: left;" class="portfolio-category" /><br />
<br />
<br />
<input type="text" name="categories" id="portfolio-categories" />
jQuery -
jQuery(document).ready(function() {
jQuery(".portfolio-category").click(function() {
if(jQuery(this).is(":checked")) {
jQuery("#portfolio-categories").val(jQuery("#portfolio-categories").val()+" "+jQuery(this).val());
}
else {
var portfolioCategories = jQuery("#portfolio-categories").val();
alert("before + "+portfolioCategories);
var currentElement = jQuery(this).val()+" ";
alert(currentElement);
portfolioCategories = portfolioCategories.replace(currentElement, "");
alert(portfolioCategories);
}
});
});
Well basically what I would like to achieve is, when user checks the checkbox, the value automatically adds inside input field (Done, it's working, whooray!), but the problem is when it unchecks the checkbox, the value should be removed from input box (the problem starts here), it doesn't remove anything. You can see I tried assigning val() function to variables, but also without success. Check my example on jsFiddle to see it live.
Any suggestions? I guess replace() is not working for val(), is it?
So, is there any other suggestions?
I'd do this:
jQuery(document).ready(function() {
jQuery(".portfolio-category").on('change', function() {
var string = "";
$('input[type="checkbox"]').each(function() {
var space = string.length>0?' ':'';
string += this.checked?space+this.value:'';
});
$("#portfolio-categories").val(string);
});
});
FIDDLE
You have quite the issue with spaces in that input box. but we'll get to that in a moment.
first, this will kind of work (if it weren't for the spaces problem):
add this line before the last alert:
jQuery("#portfolio-categories").val(portfolioCategories);
this will work, but not always, as the last element you append doesn't have a space after it.
but if you change the 4th line to this:
jQuery("#portfolio-categories").val(jQuery("#portfolio-categories").val()+jQuery(this).val()+" ");
it will work, as it adds the space after each element, instead of before.
http://jsfiddle.net/CmNFu/5/
your issue was that you changed the values in the variable: portfolioCategories, but you haven't updated the input itself. (notice, changing the value of a string, doesn't change the value of the input it originally came from)
What you need is to insert back the string portfolioCategories into the input. Also the spaces are creating a lot of problems. You could use $.trim(str) to remove any leading and trailing spaces from a string.
Have updated your fiddle with a solution that works.
http://jsfiddle.net/CmNFu/11/
Hope this helps.
Related
I am trying to get the element with the ID 1a, 2a, 3a etc. according to whenever the function is run.
It then compares that elements value (using jQuery) with the value of the input where the function is wrong
It brings up an error saying:
TypeError: var1.toUpperCase is not a function. (in 'var2.toUpperCase()','var1.toUpperCase' is undefined)
Any help would be appreciated.
Thanks
(UPDATE usually there would be text in questionNumber like: 1, 2, 3 etc every time the another function is run.)
EDIT: Every time a different function is run, questionNumber is increased by 1. I save questionNumber's text in a variable called word. I then add the letter a to that variable. Then, I get the element that has ID of the variable word, then compare it's contents to the value of the input, but the comparison is uppercase to avoid problems. If they are equal, the input is replaced with a div with green text. Hope this makes it clearer.
function textVerify(item) {
var word= document.getElementById(($('#questionNumber').text()+'a'));
if (item.value.toUpperCase() === word.toUpperCase()){
item.style.color = "green";
$( item ).replaceWith( "<div style='color:green;'>"+word+"</div>" );
main()
} else {
item.style.color = "black";
}
<span class="ihide" id="questionNumber"></span>
<p id="1a" class="ihide">Seven</p>
<input id="1" name="Seven" type="text" value="" onkeyup="textVerify(this)" autofocus="">
The var word is p tag, so you need to get the inner text of it and compare it with the input text. Also, when replacing it, access the text() property of it. See below. main() is commented out here, but you can keep as per the need.
function textVerify(item) {
var word = document.getElementById(($('#questionNumber').text() + 'a'));
if (item.value.toUpperCase() === $(word).text().toUpperCase()) {
item.style.color = "green";
$(item).replaceWith("<div style='color:green;'>" + $(word).text() + "</div>");
//main()
} else {
item.style.color = "black";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span class="ihide" id="questionNumber">1</span>
<p id="1a" class="ihide">Seven</p>
<input id="1" name="Seven" type="text" value="" onkeyup="textVerify(this)" autofocus="">
In your code ($('#questionNumber').text()+'a') this part returns just 'a', as text of the id questionNumber is nothing.
And in your HTML there is no such id. I think you need to make this changes to your HTML code:
<span class="ihide" id="questionNumber">1</span>
This should work.
EDIT: Also, can you please share the JS code associated with 'item', there can be an error in that part too.
I have a ID with special characters. I need to get the value of this input with JQUERY.
<input style="text-align:center; width:50px;" type="text" onKeyPress="jq(this.id);" value="5" id="adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG">
<script>
function jq(str) {
var id = str.replace(/[%#;&,\.\+\#*~':"!\^\$\[\]\(\)=>|\/\\]/g, '\\\\$&');
var value = $("#"+id).val();
alert(value);
}
</script>
I try with this, but i dont have response in the alert.
Help! please!
Normally you can use jQuery's escape sequence in a selector, \\, to escape special characters. However that won't work in this case as the id you have specified in the element is invalid as it contains spaces.
Due to that you will have to use the attribute selector in jQuery to retrieve it:
var $el = $('[id="adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG"]');
console.log($el.val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input style="text-align: center; width: 50px;" type="text" onKeyPress="jq(this.id);" value="5" id="adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG">
A much better solution would be to fix the id of your elements before they are output in to the page to remove the spaces and special characters.
Get the answer from fiddle here
I have written in both javascript & jquery. There is an option fot trying // before every special character in ID, but that doesn't worked for me. So on the other way you can get the answer. Check & let me know.
$("#clickID").on('click', function(){
getVal = $(document.getElementById('adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG')).val();
console.log(getVal);
alert(getVal);
});
function jq(str) {
var element = document.getElementById("adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG");
var value = $(element).val();
alert(value);
}
I have a hidden div with a simple form:
<div id="mb_clookup" style="display: none;">
<strong><font color="#0066CC">Search for existing customers</font></strong><br /><br />
<font color="#FFF">
Postcode: <input type="text" name="cl_zipcode" id="cl_zipcode" />
<span id="cl_search">Search</span>
</font>
</div>
This is displayed when the user clicks a button on the page. The user puts in the ZIP code, click on search and a JSON query is called. I have managed to make the Search button work with .live() but I cannot get the value of the input field. Here is the code:
$(document).ready(function(){
$(document).on( "click", "#cl_search", function() {
var pc = $('#cl_zipcode').val();
if(pc === '') {
alert('Please type in a post code first.');
}
else {
// JSON
}
});
});
Th pc variable comes up empty. I tried:$(this).find('#cl_zipcode').val() this comes up with undefined.
Please advise.
You can use the following
var pc= $("#mb_clookup").find('#cl_zipcode').val();
or
var pc= $("#mb_clookup :input").val();
check fiddle
With regard to $(this).find('#cl_zipcode').val() the input elements is beside the clicked span, so your find will search from the span on down (and it contains nothing aside from the text).
You need to move up the DOM first before you find it.
$(this).parent().find('#cl_zipcode').val()
Please note that as IDs are unique, so your original code is actually fine (so long as you only have one of these added): http://jsfiddle.net/TrueBlueAussie/djqfharu/
If you load more than one of these (you mention dynamic adding of fields) you will need to switch to classes to identify the elements.
e.g
$(document).ready(function(){
$(document).on( "click", ".cl_search", function() {
var pc = $(this).parent().find('.cl_zipcode').val()
if(pc === '') {
alert('Please type in a post code first.');
}
else {
// JSON
}
});
});
This is because browser keeps a fast-lookup dictionary, of IDs vs DOM elements, so only a single entry is retained per ID. The upshot of that is that jQuery can only ever find the first matching element for a search of a duplicated ID. The solution there is to switch to using classes and class-based searched.
I strongly suggest you post the rest of your code as the part shown is not the problem in isolation.
i thing your html code wrong. Becouse tag not in use tag
tag not support HTML5..
change this
<div id="mb_clookup" style="display:block;">
<strong><font color="#0066CC">Search for existing customers</font></strong><br /><br />
<span style="color="#FFF">
Postcode: <input type="text" name="cl_zipcode" id="cl_zipcode" />
<span id="cl_search">Search</span>
</span>
</div>
good luck
Your code is working fine i checked it in jsfiddle by removing display none attribute. You can check it here
HTML
<div id="mb_clookup">
<strong><font color="#0066CC">Search for existing customers</font></strong><br /><br />
<font color="#FFF">
Postcode: <input type="text" name="cl_zipcode" id="cl_zipcode" />
<button id="cl_search">Search</button>
</font>
</div>
JS
$(document).ready(function(){
$(document).on( "click", "#cl_search", function() {
var pc = $('#cl_zipcode').val();
if(pc === '') {
alert('Please type in a post code first.');
}
else {
alert(pc);
}
});
});
I have the following string.
<span class="add">foo bar1</span>
Now I have to check the last character in this string.If the last character in this string is 1,add a space to the end of the string and move the cursor out of the span tag, Else if the last character in this string is not 1,just move the cursor out of the span and do not add a space.
So can anyone help me how it can be done in javascript.This will happen when I click a button 'Done'. I am quite new to stackoverflow.So if I made q mistake in the question,please forgive me.
Thanks
Is this what you are looking for? This will loop through all elements with the tag
You should add an ID to the tag in HTML
<span class="add" id="test">foo bar1</span>
<br /><br />
<button onclick="addSpace()">Button</button>
Then use the following JS:
function addSpace() {
var testElem = document.getElementById("test");
var contents = testElem.innerHTML;
if (contents.slice(-1) === "1") {
testElem.innerHTML=testElem.innerHTML + "----";
}
}
I made a fiddle
http://jsfiddle.net/nJeyz/2/
You can't move the mouse of the user, that's impossible. However, you can revert focus to an arbitrary element instead.
<button onclick="mine()">Click</button>
<input id="testdiv">
<span id="test">foo bar1</span>
<script>
function mine() {
$string = document.getElementById("test").innerHTML;
if ($string.substring($string.length-1) == "1")
document.getElementById("test").innerHTML+= " ";
document.getElementById('testdiv').focus();
}
</script>
I'd like to save the newly entered values, so I could reuse them. However, when I try to do the following, it does not work:
// el is a textbox on which .change() was triggered
$(el).attr("value", $(el).val());
When the line executes, no errors are generated, yet Firebug doesn't show that the value attribute of el has changed. I tried the following as well, but no luck:
$(el).val($(el).val());
The reason I'm trying to do this is to preserve the values in the text boxes when I append new content to a container using jTemplates. The old content is saved in a variable and then prepended to the container. However, all the values that were entered into the text boxes get lost
var des_cntr = $("#pnlDesignations");
old = des_cntr.html();
des_cntr.setTemplate( $("#tplDesignations").html() );
des_cntr.processTemplate({
Code: code,
Value: val,
DivisionCode: div,
Amount: 0.00
});
des_cntr.prepend(old);
This is the template:
<div id="pnlDesignations">
<script type="text/html" id="tplDesignations">
<div>
<label>{$T.Value} $</label>
<input type="text" value="{$T.Amount}" />
<button>Remove</button>
<input type="hidden" name="code" value="{$T.Code}" />
<input type="hidden" name="div" value="{$T.DivisionCode}" />
</div>
</script>
</div>
You want to save the previous value and use in the next change event?
This example uses .data to save the previous value. See on jsFiddle.
$("input").change(function(){
var $this = $(this);
var prev = $this.data("prev"); // first time is undefined
alert("Prev: " + prev + "\nNow: " + $this.val());
$this.data("prev", $this.val()); // save current value
});
jQuery .data
If you want old/Initial text box value, you can use single line code as follows.
var current_amount_initial_value = $("#form_id").find("input[type='text']id*='current_amount']").prop("defaultValue");
If you want current value in the text box, you can use following code
$("#form_id").find("input[type='text']id*='current_amount']").val();