Toggle textarea text, but retain changes to the text - javascript

I'm trying to use a checkbox to disable and enable a textarea, toggling text in the box at the same time. My only issue is that I can't retain the changes that I make when the textarea is enabled. The textarea is disabled initially and holds initial text. After the textarea is enabled, the text becomes editable. If the checkbox is re-checked, the changes disappear and the orginal text re-appears-- toggling back removes the changes (which is not what I want). I'd like to toggle the text back and forth, but without removing the changes. I believe that the best way to do this is to retain the changes in a variable? I've copied the code below:
function toggleDisabled(_checked) {
document.getElementById('tjh').disabled = _checked ? true : false;
document.getElementById('tjh').value= "initial text";
}
<form>
<input type="checkbox" checked name="name1" onchange="toggleDisabled(this.checked)"/>
<textarea disabled name="name2" id="tjh">initial text</textarea>
</form>

You don't need to read the value from the textarea and store it into a variable every time the checkbox is checked or unchecked. You also don't need to (or should) set the initial value for the textarea in your javascript. Set the initial textarea content in the HTML and then use javascript to attach event listener to the checkbox that will add/remove the disabled attribute from the element based on whether checked or not.
You can use the onChange attribute on the HTML element and pass in a javascript function as you originally had, but IMO doing so unnecessarily couples the HTML and Javascript together; making it harder to make changes and read.
<form>
<input type="checkbox" checked name="name1" id='name1' />
<textarea disabled name="name2" id="tjh">Initial text</textarea>
</form>
<script type='text/javascript'>
// Grab HTML elements by element's id
var txtBox = document.getElementById('tjh');
var checkBox = document.getElementById('name1');
var customText = 'initial text';
// Attach event listener to checkbox
checkBox.addEventListener('click', function(evt, el) {
// If checked, then save current textarea value and disable textarea
if (evt.target.checked) {
customText = txtBox.value;
txtBox.value = 'initial text';
txtBox.setAttribute('disabled', evt.target.checked);
}
// Otherwise restore text and reenable the textarea by removing disabled attribute from HTML element
else {
txtBox.value = customText ;
txtBox.removeAttribute('disabled');
}
}, false)
</script>
EDIT: Added customText variable to store/restore txtBox values on disable/enable of checkbox

If I'm understanding correctly, can't you just store the text in a variable?

Related

ko binding for checkbox: change 'checked' attr from code not change the observable field

I have checkbox at html that is binding to observable-field (field of breeze entity).
<input id="chk1" type="checkbox" data-bind="checked: data().isBirthday"/>
The binding works well from the tow sides:
When I write at code:
data().isBirthday(true);
the checkbox become checked.
and when I write at code
data().isBirthday(false);
the checkbox become unchecked.
And when I choose the checkbox by clicking with mouse - the observable field gets value of true. (Or when I unchecked by mouse - it gets value of false).
sometime, I need to change the checked attribute of the checkbox by code, specifically by retrive checkbox with jquery.
(I cannot do it by the observable field becouse of any reasons).
I do:
var control = $('#chk1')[0];
control.checked = false;
but this not change the value of the binded observable-field. It continue holding true value.
I tried to triiger the change event:
$(control).change()
It didn't help.
So, what should I do?
Here is an example:
https://jsfiddle.net/kevinvanlierde/72972fwt/4/
Can we see the html code?
Try $('#chk1').prop("checked", false);

Changing a label, using Query, when it has the form element inside

I am attempting to change the form label below using Jquery but found that changing the HTML removed the form element inside the label. Can anyone show me how I can change the lable text without removing the form element. Thanks!
<label for="field_217-0">
<input id="field_217-0" type="radio" value="Yes" name="item_meta[217]"></input>
Yes
</label>
Lets say I want to change above to 'Yes Sir!'
So far all I have is:
jQuery(document).ready(function($){
$(document).ready(function() {
$("label[for='field_217-0']")
});
});
You can save the input and then replace the contents with the input and the new label:
var label = $("label[for='field_217-0']");
var input = label.find("input");
label.html(input).append("New Label");
...also you don't need the duplicate .ready() layers.

Dynamically creating input elements onclick

Hey guys so I am creating input elements within a div when I click on a specific radio button with a javascript function.
It works great but when I first load the form the input elements dont appear in the div because the radio button has not been "clicked yet" although one of the radio buttons is default checked.
Basically if its checked I want them to appear, so on body load I have to call a function that checks the radio button I want default and I have to manually display the corresponding input elements that would appear if I had clicked the radio button.
This seems like a dumb work around of what I am trying to achieve, any ideas?
<body onload="startup()">
<input type="radio" name="type" onclick="createInput()" id="testradio" value="test">test</input>
<div id="area">
</div>
</body>
function startup()
{
document.getElementById("testradio").checked = true
createInput();
}
function createInput()
{
var testinput = "<input name='options' value='testing' type='checkbox'>test<br>"
document.getElementById("area").innerHTML = testinput
}
You should set the default value and then call the event. (say onchange)
something like this:
document.getElementById('elID').onchange();
this will then let your event listener fire as if the value where changed in the ui not in code.

Inner HTML with input values

have a brief question regarding innerHTML and input values that have been entered. See the brief example below (using jQuery for convenience):
http://jsfiddle.net/F7urT/2/
jQuery:
jQuery(document).ready(function($) {
$('.send').click(function() {
alert( $('.content').html() );
return false;
});
});​
html:
<div class="content">
<input type="text" name="input" value="Old Value" />
<input type="button" class="send" value="Send" />
</div>​
If you edit the input value, then click the 'Send' button, the alert shows that the innerHTML gotten contains the input with the "Old Value", rather than the value the user has entered. Why is this? And how can we get the HTML as a string with user entered input values?
The new value is stored as a property not an attribute, the value can be obtained by inputelement.value, modifying the value does not affect the attribute. If you want the html with the new value just set the attribute to the new value.
For check boxes and radio buttons set the checked attribute, set the innerHTML for text areas, for selects set the selected attribute on the option
http://jsfiddle.net/mowglisanu/F7urT/5/
this solution is better. works for more inputs.
$('input[type=text]').attr('value', function (i, val) { return val; });
$('input[type=checkbox],input[type=radio]').attr('checked', function () { return this.checked; });
$('textarea').html(function () { return this.value; });
$('select').find(':selected').attr('selected', 'selected');
You can't get it with .innerHTML (.html()). Writing into an element doesn't modify the html markup, nor will it change the value attribute in actual markup.
You can only access the current content by directly asking the element for its .value - value. Using jQuery, you can do that via .val() too.
$('#input_id').attr('value',$('#input_id').val()); will put the value into the html
DanCZ & Musa solutions works pretty good, but I had trouble with the textarea.
I have to implement this in a Typescript project and the only way I've found to make the textarea show the value is this :
textarea.innerHTML = textarea.value;

javascript/jquery- parsing through all elements of a radio/check box- how to get text value of each element

I am trying to parse through a checkbox/radio button.
As an example let us consider the html code for a radio button below--
<br/><br/>Lunch-
<input type="radio" name="lunch" value="pasta1" /> Pasta
<input type="radio" name="lunch" value="rissotto1" /> Rissotto
<br/>
Now I am using the following code to obtain both the text value shown on screen (eg "Pasta") as well as the value assigned (eg "pasta1")--
$(jQuery('input[type="radio"], input[type="checkbox"] ', $(element).parent('form'))).each(function()
{
alert(" Text values =" + $(this).text());
alert(" actual values =" + $(this).val());
---SOME MORE CODE---
}
As output, I am not getting any value when I use $(this).text(), although $(this).val() works fine.
How do I get the text values for each element of a radio button/check box... Something that I can use in place of the $(this).text() used above? Is there some other way to obtain the text value (eg "Pasta" or "Risotto" for the example above)?
I don't think you can retrieve the text value with the HTML you have. Ideally you should create label elements to hold the text. e.g.
<input type="radio" name="lunch" value="pasta1" /> <label>Pasta</label>
<input type="radio" name="lunch" value="rissotto1" /> <label>Rissotto</label>
Then you can get the text:
$(this).next().text();
EDIT:
If you can't change the HTML, here is a dirty workaround.
Assuming you have a wrapper element (form or div) of id wrapper around these radio buttons and each radio button has unique value-
/*
* Create mapping between radio button values and texts
*/
var mapping = new Array();
var current_key = '';
$('#wrapper').contents().each(function()
{
if(current_key)
{
mapping[current_key] = $(this).text();
current_key = '';
}
if($(this).attr('type') == 'radio')
{
current_key = $(this).val()
}
});
Then you can easily use the mapping:
$('input[type=radio]').each(function()
{
text = mapping[$(this).val()];
})
.text() is not applicable for those elements who don't have close tag. e.g. <INPUT> <IMG> If you read the documentation of .text() it is clearly written that The .text() method cannot be used on form inputs or scripts.
I'm not sure what you exactly wanted to be shown but giving value attribute will show a text next to Radio Button. Thats how it works. I'm not sure why you want another extra text after that. But if thats the case then solution suggested by #Vikk is right.

Categories

Resources