I am doing something like this:
var MESSAGE = "part1 part2";
var fName = $("<input type=\"text\" class=\"fieldname\" size=35 disabled=disabled value=" + MESSAGE + " />" );
the value of the textbox turns out to be "part1" and is missing part2. i.e the characters after the whitespace . What is the mistake here?
You should add " to your value:
var MESSAGE = "part1 part2";
var fName = $("<input type=\"text\" class=\"fieldname\" size=35 disabled=disabled value=\"" + MESSAGE + "\" />" );
Otherwise your browser interprets "part2" to be a new attribute like "class" or "size".
One improvement could be to use the jQuery .attr() function, since it automatically escapes HTML entities such as ". It is recommended to do so, unless you are absolutely sure that your message doesn't contain any ",<or >.
var MESSAGE = "part1 part2";
var fName = $("<input">).attr({
type : "text",
class : "fieldname",
size : "35",
disabled : "disabled",
value : MESSAGE
});
And now you are safe.
Related
I have four radio buttons, the last being an option for "other." Clicking this radio button reveals a hidden text field so the user can explain further. This is part of a larger form that creates an email based on the options the user chose. Basically, the four radio buttons/other field need to be combined so the user's answer to that section shows up in the email, whether they pick a radio button or type in their own response. Here's my HTML:
<h1>Reason</h1>
<input type="radio" name="reason" class="reason" value="Customer requesting escalation" onclick="document.getElementById('hiddenOtherField').style.display='none'" checked>Customer requesting escalation<br>
<input type="radio" name="reason" class="reason" value="Workaround lost" onclick="document.getElementById('hiddenOtherField').style.display='none'">Workaround lost<br>
<input type="radio" name="reason" class="reason" value="Resolution overdue" onclick="document.getElementById('hiddenOtherField').style.display='none'">Resolution overdue<br>
<input type="radio" name="reason" class="reason" id="otherRadioBtn" onclick="document.getElementById('hiddenOtherField').style.display='block'">Other...<br>
<div id="hiddenOtherField" style="display: none">
<input type="text" name="reason" id="otherFreeTextField" placeholder="Please explain...">
</div><br>
I'm getting the selected value of this "Reason" section from jQuery:
$(".reason:checked").val()
But when "Other" is checked, the value of $(."reason") is "on" instead of whatever they typed. I have no idea why or how or where the word "on" comes from (it's nowhere in my code). I know I'm missing something but I don't know what. How would I make it so if the user selects the "other" radio button, whatever they type into the text field becomes the value for "reason"? I've tried a bunch of different if statements, but it's been hours and nothing is working. Please help! Thanks!
Edit - here is the Javascript code I'm using to display my values. Again, this is all a custom HTML form used to create an email based on the options the user chose. All of the other things here I'm getting the values of are working because they're straightforward.
function generateEmail() {
var emailTo = $("#teamName").val();
var emailCC = $("#CC").val();
var emailSubject = $("#ticketNumber").val();
var emailBody = "Issue: " + $("#issue").val() + "%0A%0ACustomer Contact Information: " + $("#contactInformation").val() + "%0A%0ARequested Action: " + $(".requestedAction:checked").val() + "%0A%0AReason: " + $(".reason:checked").val() + "%0A%0AWorkaround Available? " + $(".workaround:checked").val();
location.href = "mailto:" + emailTo + "?cc=" + emailCC + "&subject=" + emailSubject + "&body=" + emailBody;
};
I'm using a button at the end of my form to generate the email:
<input type="submit" value="Generate email" onclick="generateEmail()">
If you want to get the input value that the user typed you need to use :
$("#otherFreeTextField").val()
So you have to add a check if the other is checked then the reason will be the value of the input :
var reason = $(".reason:checked").val();
if( $('#otherRadioBtn').is(':checked') ) {
reason = $("#otherFreeTextField").val();
}
As a shortcut you could use :
$('#otherRadioBtn').is(':checked')?$("#otherFreeTextField").val():$(".reason:checked").val();
In you context the condition should be injected like :
function generateEmail() {
var emailTo = $("#teamName").val();
var emailCC = $("#CC").val();
var emailSubject = $("#ticketNumber").val();
var reason = $('#otherRadioBtn').is(':checked')?$("#otherFreeTextField").val():$(".reason:checked").val();
var emailBody = "Issue: " + $("#issue").val() + "%0A%0ACustomer Contact Information: " + $("#contactInformation").val() + "%0A%0ARequested Action: " + $(".requestedAction:checked").val() + "%0A%0AReason: " + reason + "%0A%0AWorkaround Available? " + $(".workaround:checked").val();
location.href = "mailto:" + emailTo + "?cc=" + emailCC + "&subject=" + emailSubject + "&body=" + emailBody;
};
This is happening because you are checking the status of textbox if visible or not.$(".reason:checked").val(). That's why it's giving on cause it's visible.
Try: $(‘.reason:textbox’).val()
`
$(function(){
$('.addLink').click(function(e){
e.preventDefault();
var content = $('.categorySelect');
var url = $("#userInput").val();
var link = "<a href='" + url + "'>" + "<br />" + url + "</a>";
$(link).appendTo('.sports');
});
});
Choose Category:
<select class='categorySelect'>
<option value="Sports" id="a">Sports</option>
<option value="World" id="b">World</option>
<option value="Movies" id="c">Movies</option>
</select><br />
<input type='text' id='userInput' placeholder='Enter Link Here' />
<input type='button' value='Add' class='addLink'/>
<div class='sports'>
Sports:
</div>
<div class='world'><br />
World:
</div>
<div class='movies'><br />
Movies:
</div>
</div>
`heres what i have now. when the user chooses a catergory from the dropdown menu their typed in link will show under that caterory(div class). i cant seem to figure this out.
$('.addLink').click(function () {
var content = $('.categorySelect').val().toLowerCase();
var url = $("#userInput").val();
var link = "<a href='" + url + "'>" + "<br />" + url + "</a>";
$(link).appendTo('.'+content);
});
jsFiddle Demo
First, you don't need event.preventDefault() because the input field doesn't have a default action that needs to be suppressed (cf. the a tag, which does).
Next, you need to grab the value of the SELECT and convert to lowercase, since that is the case of the class.
To append to the correct class, you concat the . class indicator to the name of the class extracted from the SELECT option value.
If you wanted to make the action automatic upon selection of a category, then change this:
$('.addLink').click(function () {
to this:
$('.categorySelect').change(function () {
Revised jsFiddle
Note how we can use $(this) to refer to the control that triggered the event. By using $(this), we can chain jQuery methods, e.g.
var content = $(this).val();
If all we want is the value, we can use pure javascript as it is a bit faster:
var content = this.value;
Since .toLowerCase() is pure javascript, we can still go with this.value
var content = this.value.toLowerCase();
I have wrote some working code for you, with comments included on Fiddle:
$(function(){
$('.addLink').click(function(e){
e.preventDefault();
/*
Select the value of the dropdown (lowercase the values because your
HTML classes are written lowercase) and the values of your dropdown are not.
*/
var content = $('.categorySelect').val().toLowerCase();
var url = $("#userInput").val().toLowerCase();
var link = "<a href='" + url + "'>" + "<br />" + url + "</a>";
//Save check if the user has filled in a URL.
if(url !== '')
//append URL link to the selected value of the dropdown.
$(link).appendTo('.'+content);
});
});
http://jsfiddle.net/9fc8zb4b/
Using Digital Bush's maskedInput plugin to format a phone number and then breaking that phone number out of the mask and into a div. I need to split that divs content into 3,3,and 4... i.e. I need to break it into 3 inputs (which will eventually be hidden) to send that back to the server. So far I have everything working except the split and I may be using that wrong instead of breaking it up using length.
Here is a working fiddle of what I have right now:
JS FIDDLE
I have this right here:
<input id="txtPhoneNumber" name="FancyPhoneNumber" class="required phone" type="text" />
<div id="txtHiddenPhoneNumber2"></div>
Which takes the users input and puts the stripped down value (10 numbers) into a div. Then I am taking that div and putting it into three input fields.
$("#txtPhoneNumber").mask("(999) 999-9999");
$("#txtPhoneNumber").blur(function () {
$("#txtHiddenPhoneNumber").val("");
var charArray = $(this).val().split("");
var phoneNumber = "";
$.each(charArray, function(index, value) {
if (!isNaN(value) && value != " ") {
phoneNumber = phoneNumber + value;
}
});
$("#txtHiddenPhoneNumber2").append("<div>"+phoneNumber+"</div>")
var data =$('#txtHiddenPhoneNumber2').text();
var arr = data.match(/.{3}/g);
$("#txtHiddenPhoneNumber2").html("<input type=\"text\" value='"+arr[0] +"'>" + "<input type=\"text\" value='"+arr[1]+"'>" + "<input type=\"text\" value='"+arr[2] +"'>");
});
It's working as I need only it is not sending the last digit to the last input field which is being populated with arr[2]. I assume I am trying to use split wrong. Any ideas?
Try this code
$(document).ready(function() {
$("#txtPhoneNumber").mask("(999) 999-9999");
$("#txtPhoneNumber").blur(function () {
$("#txtHiddenPhoneNumber").val("");
var data =$("#txtPhoneNumber").val();
var arr = data.match(/\d{3,4}/g);
$("#txtHiddenPhoneNumber2").html("<input type=\"text\" value='"+arr[0] +"'>" + "<input type=\"text\" value='"+arr[1]+"'>" + "<input type=\"text\" value='"+arr[2] +"'>");
});
});
I have a String "Magic Word". I need to use it as value in html checkbox generated by javascript.
in javascript
var itemValue= "Magic task";
var opt = "<input type='checkbox' name='test' id='test' value="+ itemValue+ "/>"+itemValue+ "<br />";
alert(opt);
$(optionDiv).append(opt);
In alert it is displaying the actual value but after submitting form i am getting only first word as value.It is ignoring second word.
Thanks
Ravi Kant
You need to wrap the value with single quotes:
"<input type='checkbox' name='test' id='test' value='" + itemValue + "' />"
If you are using jQuery (as I see the usage of $ in your code), it's better to do it with jQuery itself:
var itemValue= "Magic Word";
var opt = $('<input>').attr({
type: 'checkbox',
name: 'test',
id: 'test',
value: itemValue
});
It will prevent any furthur error, for example if you have some ' in your string:
var itemValue= "Magician's Word";
When you do not use quotes the attributes value ends at the whitespace. Your rendered string appears as
<input type='checkbox' name='test' id='test' value=Magic Word />
So the parser sees
value=Magic
and an attribute Word with no value. You can see that with the coloring in the post above.
You need to add single quotes around the value
var opt = "<input type='checkbox' name='test' id='test' value='" + itemValue + "' />"+ itemValue+ "<br />";
^ ^
Where does this fail? If you have a ' in your string. You would need to add a replace method and swap it for #apos;
itemValue = itemValue.replace(/'/g,"#apos;");
I have a form input text field, and I want to change the text inside of the text field when the user clicks a button. I can get the specific textfield with jQuery, but cannot change the text with .val(). Is there another way this can be done, or am I doing something wrong.
Here is the text field:
<input type="text" name="textBox" id="Stage 1text" size="20" value="Enter Current Comp." align="center">
Then I use this to identify and change the text field. where in this case stage = "Stage 1" and dance is the string I want to place in the text field.
str = "#" + stage + 'text';
alert(str + '::' + dance); // confirm that strings are correct
jQuery(str).val(dance);
An ID should not have spaces. Stage 1text is an invalid ID
Add an underscore instead of space
<input type="text" name="textBox" id="Stage_1text" size="20" value="Enter Current Comp." align="center">
and try below,
// v--- assuming this will be Stage_1
str = "#" + stage + 'text';
alert(str + '::' + dance); // confirm that strings are correct
jQuery(str).val(dance);
incase if stage is returned from backend.. then simply replace space with _
str = "#" + stage.replace(/ /g,"_") + 'text';
id attributes should not contain spaces.
You could change your code like so:
<input type="text" name="textBox" id="Stage_1text" size="20" value="Enter Current Comp." align="center">
str = "#" + stage.replace(' ','_') + 'text';
alert(str + '::' + dance); // confirm that strings are correct
jQuery(str).val(dance);