I've got this code
HTML
<h2 class="p1">Player 1</h2>
<input type="text" class="addName1" value="Player 1"></input><button class="addName1b">Add name</button>
Jquery
$('.addName1b').click(function() {
var $this = $(this);
$this.toggleClass('addName1b');
if ($this.hasClass('addName1b')) {
$this.text('Add name');
} else {
$this.text('Change name');
}
$('.addName1').toggle();
$(/*TEXT FROM INPUT*/).appendTo(".p1");
});
I want the Player 1 to change into the text from the input box when I press the button but can't figure out how. Help please :)
As you can see I was planning on using .appendTo but I don't know how to access the text from the input element.
Thanks
Use it this line of code
$('.p1').text($('.addName1').val());
in the place where you have $(/*TEXT FROM INPUT*/).appendTo(".p1");
appendTo is not the right choice for your goal here, appendTo is used to append elements into another, but your requirement is to change the text of the element, you must use .text()
Here is a working snippet.
$('.addName1b').click(function() {
var $this = $(this);
$this.toggleClass('addName1b');
if ($this.hasClass('addName1b')) {
$this.text('Add name');
} else {
$this.text('Change name');
}
$('.addName1').toggle();
$('.p1').text($('.addName1').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2 class="p1">Player 1</h2>
<input type="text" class="addName1" value="Player 1"></input><button class="addName1b">Add name</button>
Used a variable to store the new name,
Got the new name from the input using .val()
Reversed the last line because the selector $('.p1')goes first then the value is last (newName).
There's no parentheses because it's a variable representing a string.
Change the last two lines to this:
var newName = $('.addName1').val();
$(".p1").text(newName);
$(function() {
$('.addName1b').click(function() {
var $this = $(this);
$this.toggleClass('addName1b');
if ($this.hasClass('addName1b')) {
$this.text('Add name');
} else {
$this.text('Change name');
}
var newName = $('.addName1').val();
$(".p1").text(newName);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<h2 class="p1">Player 1</h2>
<input type="text" class="addName1" value="Player 1" />
<button class="addName1b">Add name</button>
Maybe you should use some framework?) Something like angular, knockout, reactjs? Excellent for something like this purposes.
But. For reading input value you can use something like:
$('#id').val();
Input does not close like this
<h2 class="p1">Player 1</h2>
<input type="text" class="addName1" value="Player 1"></input><button class="addName1b">Add name</button>
just
<input .... />
Your JS - modified
$('.addName1b').click(function() {
var $this = $(this);
var $input_val = $('.addName1').val();
$this.toggleClass('addName1b');
if ($this.hasClass('addName1b')) {
$this.text('Add name');
} else {
$this.text('Change name');
}
$('.addName1').toggle();
$('.p1').text($input_val);
});
here's jsfiddle: https://jsfiddle.net/qgumjy7b/
Hope this helps to understand what are you missing.
Related
I am building a contact form, and I am having problems with jQuery. I want to select specific input fields that have an error and apply the class err. Unfortunately, my code selects all inputs when there is an error. I am having trouble identifying which part of my logic is wrong.
$('#send_mail').click(function(){
$("#contact_body").find('label').each(function(){
var contact_label = $('input[required=true], textarea[required=true]');
var label_check = $(this).find(contact_label);
$(contact_label).removeClass('err');
if (!$.trim($(label_check).val())){
$(contact_label).addClass('err');
}
});
});
The order of my HTML goes something like so:
#contact_body
<label>
<input>
</label>
This selects all input and textarea elements:
var contact_label = $('input[required=true], textarea[required=true]');
Instead, you should restrict it to the elements within the label:
var contact_label = $(this).find('input[required=true], textarea[required=true]');
Note that $(contact_label) and contact_label are equivalent in your code, as well as $(label_check) and label_check.
Also, you can use the state parameter of toggleClass() to simplify this:
contact_label.removeClass('err');
if (!$.trim(label_check.val())){
contact_label.addClass('err');
}
… to this:
contact_label.toggleClass('err', !$.trim(label_check.val()));
Here's the updated event:
$('#send_mail').click(function(){
$('#contact_body').find('label').each(function(){
var contact_label = $(this).find('input[required=true], textarea[required=true]');
var label_check = $(this).find(contact_label);
contact_label.toggleClass('err', !$.trim(label_check.val()));
});
});
I think your original code would work if you just changed this line:
$(contact_label).addClass('err');
To this:
$(label_check).addClass('err');
Because $(contact_label) references all the required inputs, whereas $(label_check) references only the input being checked.
But your code could be simplified, and you make unnecessary calls to $(), giving it an argument that is already a JQuery object.
I also do not see that you need to loop through the labels. You could loop through the required inputs instead.
$('#send_mail').click(function(){
$("#contact_body").find(':input[required]').each(function() {
var $input = $(this);
$input.removeClass('err');
if (!$.trim($input.val())){
$input.addClass('err');
}
});
});
Which could be shortened by using the .toggleClass() function:
$('#send_mail').click(function(){
$("#contact_body").find(':input[required]').each(function() {
$(this).toggleClass('err', !$.trim($input.val()));
});
});
Notes:
The selector ':input' matches <input>, <select> and <textarea> elements.
This is a slightly different approach. Gives a bit more flexibility.
arr = ['first', 'last', 'email', 'msg']; //IDs of fields to check
$('#send_mail').click(function(){
$('input, textarea').removeClass('err');
for (var i=0; i<arr.length-1; i++) { //Loop through all field IDs
if ( $('#'+arr[i]).val() == '' ) {
$('#'+arr[i]).addClass('err').focus();
return false;
}
}
//AJAX to send email goes here
alert('Email sent');
});
.err{background:yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="first">First Name:</label>
<input id="first" type="text" required /><br>
<label for="last">Last Name:</label>
<input id="last" type="text" required/><br>
<label for="email">Email:</label>
<input id="email" type="email" required /><br>
<label for="msg">Message:</label>
<textarea id="msg" required></textarea>
<button id="send_mail">Send</button>
you can simplify the code, there will be less mistakes:
$('#send_mail').click(function(){
$("#contact_body").find('label').each(function(){
var field = $(this).find('[required=true]');
if ($.trim($(field).val())){
$(this).removeClass('err');
}
});
});
This is a form I have:
<h1>Word game!</h1>
<form id="joke-form">
<label>
Unscramble these letters to form a word:<Br>
<span class="scrambled">REYJUQ</span>
<br>
<input type="text" id = "userinput" size="10">
</label>
<button type="submit">Check</button>
</form>
And here is a jquery function I am running on it. My problem is that I don't know how to get the value that the user inputs in the textbox when they press submit. I am relatively new to jquery but have had no luck in researching this topic, including reading similar questions on this site.
<script>
$('#joke-form').on('submit', function(event) {
event.preventDefault();
var words = $('this input: first').val();
console.log(words);
});
if (words === "ANSWER") {
$('#result').text("You have the right answer");
}
else {
$('#result').text("Guess again!");
}
</script>
You have the code in the wrong place, and the selector you are using is incorrect for the input.
See this codepen on how this could work:
http://codepen.io/KempfCreative/pen/JGRzwm
$('#joke-form').on('submit', function(event) {
event.preventDefault();
var words = $('#joke-form #userinput').val();
console.log(words);
if (words === "ANSWER") {
$('#result').text("You have the right answer");
}
else {
$('#result').text("Guess again!");
}
});
Try:
var words = $('#userinput').val();
Your selector $('this input: first') is malformed. Since your input element has an id anyway, I would just select it by id instead. Also you will need to put your if else statement inside the submit function.
Here is a Live Demo of your code working in action:
$('#joke-form').on('submit', function(event) {
event.preventDefault();
var words = $('#userinput').val();
console.log(words);
if (words === "JQUERY") {
$('#result').text("You have the right answer");
} else {
$('#result').text("Guess again!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Word game!</h1>
<form id="joke-form">
<label>
Unscramble these letters to form a word:
<Br>
<span class="scrambled">REYJUQ</span>
<br>
<input type="text" id="userinput" size="10">
</label>
<button type="submit">Check</button>
</form>
<span id="result"></span>
JSFiddle Version: https://jsfiddle.net/6pd5z9kv/1/
I see many anwsers already but here is what you've done wrong
your code
var words = $('this input: first').val();
fixed
var words = $(this).find("input:first").val();
//use 'this' seprately, then you start input:first with " and finished with '
hopefully it will work for you, and about html I dont know if its copy/pase issue but remove blank space with id and =
your code
id = "userinput"
fixed
id="userinput"
Rest is just fine :)
Cheers
i'm working on a small html form with 1 textbox input, after the user enters any text and he presses a button on the end of the page i want the to change to a normal plain html text(so the whole page can be copy pasted into a word file including the written down text in the textbox).
as an example:
<input type="text" id="fileserver">
<button onclick="disable_all();">click!</button>
after the button is pressed i want the textbox to be converted to plain html text with no more textbox like this:
this is an example text after pressing the button!
click!
i have been searching around and have not found a working solution yet, hope someone can help me out
$('button').click(function(){
$('body *').replaceWith(function(){
return this.value || this.innerHTML;
});
});
http://jsfiddle.net/pYw9P/
This should do it I think.
function disable_all() {
var fs = $("#fileserver"), span = $( "<span>" + fs.val() + "</span>");
span.insertAfter(fs);
fs.remove(); // or fs.hide(); in case you want it later.
}
Try:
HTML:
<input type="text" id="fileserver">
<button id="but">click!</button>
JS:
$( "#but" ).click(function() {
var text=$( "#fileserver" ).val();
$( "body" ).html(text);
});
DEMO
This should be helpful to you -
There are several way to achieve your task :
Solutions 1 -
function disable_all()
{
$('#content').remove();
$('#fileserver, button').hide();
$('body').append("<div id='content'>" + $('#fileserver').val() + "</div>")
}
Working Fiddle
Solution 2 -
function disable_all()
{
$("body").html($("#fileserver").val());
}
Working Fiddle
you can do this hiding the textbox
<input type="text" id="fileserver">
<div id="result"></div>
<button id="btn" >click!</button>
and
$(document).ready(function(){
$("#result").hide();
$("#btn").click(function(){
$("#result").text($("#fileserver").val());
$("#fileserver").hide();
$("#result").show();
});
});
demo
The first "non-jQuery" answer...
your HTML:
<input type="text" id="fileserver">
<div style="display: none;" id="fileserver_text"></div>
<button id="btn">click!</button>
your Javascript:
document.getElementById('btn').onclick = disable_all;
function disable_all() {
var input = document.getElementById('fileserver');
var disp = document.getElementById('fileserver_text')
disp.innerHTML = input.value; // get the text from the input and set the div text
disp.style.display = 'block'; // show the div
input.style.display = 'none'; // hide the input
}
JSFiddle
If you are using jQUery, this will help you,
http://jsfiddle.net/DCak6/
function save(){
$('input,textarea').each(function(){
var $this = $(this);
$this.after('<span class="value">' + $this.val() + '</span>');
$this.remove();
})
}
You may be better off with taking the text from the text field, copying the value and putting it into another div
<div id="textToCopy"></div>
<input type="text" id="fileserver">
<button onclick="disable_all();">click!</button>
<script type="text/javascript">
function disable_all() {
$('#textToCopy').html($('#fileserver').val());
$('#fileserver').hide();
}
</script>
I want to place a cross button next to a text field, which, on clicking it, clears the value entered by the user. In other words, it empties the field. Please help..
And I also want to focus the field, but after some 2 or 3 seconds..
Like this:
$('#myButton').click( function () {
$('#myField').val('');
});
Or without jQuery
document.getElementById('myButton').onclick = function () {
document.getElementById('myField').value = '';
});
Try this,
$('#button').click(function(){
$('#inputBox').val('');
});
Have you tried anything at all? But this should do (edit after misread, see below):
$('#your_button').click(function() { $('#your_textbox').val(''); });
In Javascript:
document.getElementById('textField1').value = "";
Well, learn to break your tasks into smaller one and everything will become much easier. Here, for example, you have 2 tasks:
1) Place a "X" button near input. This is achieved by CSS and HTML. You HTML might look like:
Then you should align your image with you input
2) Actual erasing. In jQuery:
$("#x_button").click( function() {
$("#input_id").val( "" );
});
But this is real basics of web development, so you should really consider to read some kind of book on it.
You can do it with html5 value.
<input type="text" placeholder="Your text here">
Assuming your text field looks like this one :
<input type="text" id="myText"></input>
and your button looks like this one :
<input type="button" id="myButton"></input>
You just have to do this in javascript :
<script type="text/javascript">
var myButton = document.getElementById('myButton');
myButton.addEventListener("click", function () {
document.getElementById('myText').value = '';
}, false);
</script>
If you're using jQuery it's even easier :
<script type="text/javascript">
$('#myButton').click(function() {
$('#myText').val('');
});
</script>
here is a sample:
Html:
<input type="text" id="txtText" value="test value" />
<input type="button" id="btnClear" value="Clear" />
javascript:
$(document).ready(function () {
$("#btnClear").click(ClearText);
});
function ClearText() {
$("#txtText").val("");
}
why after two click this code adding several input together?
$('.add_input').live('click', function () {
var scntDiv = '.'+$(this).closest('div.find_input').find('div').attr('class');
var i = $('.adding').size();
var input = $(scntDiv).clone().wrap("<div>").parent().html();
alert(scntDiv)
$(scntDiv + ' .add_input').remove();
$(input).appendTo(scntDiv);
$('<div></div>').appendTo('.add_in');
$(scntDiv + ' .add_in div a:first').remove('')
i++;
return false;
});
html: (i use of this html twice)
<div class="column find_input">
<div class="ai_service">
<div class="column">
<div class="mediumCell">
<input type="text" name="name" style="width: 160px;" placeholder="خدمات دیگر" title="نام پکیج تور خارجی">
</div>
</div>
<div class="column" style="margin: 5px 3px;">
<div class="mediumCell add_in">
</div>
</div>
</div>
</div>
Hmm if you're just trying to add an extra input field, your code seems a little overcomplicated for that... Try this?
$('a.add_input').live('click', function(e) {
e.preventDefault();
var $this = $(this);
var $wrapper = $this.closest('div.find_input');
var $input = $wrapper.find('input[name=name]').eq(0).clone();
$wrapper.children('div').eq(0).append($input);
};
I didn't replicate everything from your code, just the cloning/adding new input. If you posted simplified code and my example doesn't apply, I apologize. Also, I think you wanted to append your cloned input into div.ai_service?
In terms of why your original code adds multiple inputs, the cloning process you go through probably first clones one input, adds it, clones the whole thing again (2 inputs), adds 2, and so on. You can use $().eq(0) to limit your jQuery object to the first element it finds that matches your selector.
Try this
$('a.add_input').live('click', function (e) {
e.preventDefault();
var $column = $(this).closest("div.column");
var input = $column.prev("div.column").clone().wrap("<div />").parent().html();
$column.before($(input));
});