Using document.writeln with input form in Javascript - javascript

I'm trying to input a form with Javascript. On the form, if the dropdown selection is a certain selection then specific form fields will appear below.
Here is the code I currently have, but it doesn't seem to work, I am guessing document.writeln is not the proper method. If I add an alert to see if it is pulling the selection it works, so something with adding the form in is failing. After the document.writeln the alert doesn't even come up anymore?
<script language="javascript">
var HelpTopic = document.getElementById('type');
HelpTopic.onchange=function() {
if(HelpTopic.value == "Analytics") {
alert("Congrats");
document.writeln('\<li\>
\<label for\=\"confirm\"\>Input name*\<\/label\>
\<input type\=\"text\" name\=\"inputs\" id\=\"names\" required \/\>
\<\/li\>');
} else {
alert("Fails");
}
}
</script>

You can't span a string over multiple lines in JS. You need something like this:
document.writeln('\<li\>' +
'\<label for\=\"confirm\"\>Input name*\<\/label\>' +
'\<input type\=\"text\" name\=\"inputs\" id\=\"names\" required \/\>' +
'\<\/li\>');
EDIT: You don't need so much escaping. This will work just as well:
document.writeln(
'<li>' +
'<label for="confirm">Input name*</label> ' +
'<input type="text" name="inputs" id="names" required />' +
'</li>');

To properly add list item to some list have such code instead:
var oList = document.getElementById("MyList");
var oItem = document.createElement("li");
oItem.innerHTML = "<label for='confirm'>Input name*</label><input type='text' name='inputs' required />";
oList.appendChild(oItem);
This will add item to list with ID MyList.

just a quick note, multi line strings are supported in javascript like this
'<li>\
<label for="confirm">Input name*</label>\
<input type="text" name="inputs" id="names" required />\
</li>'
I agree with Shadow Wizard, that would be the best way to append a list

The way you're trying to dynamically modify the "onChange" (missing capital C) seems to have trouble with Chrome
Also, you cant split a string over multiple lines the way you did
The following code should work, notice I added "onChange=myfunc();" to the select:
<select id=type onChange=myfunc();>";
<option value=Other>Other</option>
<option value=Analytics>Analytics</option>
</select>
<script language="javascript">
function myfunc()
{
var HelpTopic = document.getElementById('type');
if(HelpTopic.value == "Analytics") {
alert("Congrats");
document.write('<li><label for="confirm">Input name*</label><input type="text" name="inputs" id="names" required></li>');
} else {
alert("Fails");
}
}
</script>

Related

How to fill data automatically in a textfield using the info provided in the <select> tab using javascript

How to fill data automatically in a textfield using the info provided in the tab using javascript. And also the filled data cannot be edited.
The textfield may fill data based on calculation on the option selected in tab.
Please help.
I don't so much understand your question but try this:
HTML
<input type="text" id="t" disabled />
JS
var text = document.getElementById('t');
text.value = 658.57; // your calc result
If you use jQuery, you can do something like this:
$(document).ready(function() {
var VALUE_OF_SELECTED_TAB = this.value;
// HERE DO YOUR CALCULATIONS
$(YOUR_SELECT_ELEMENT).on('change', function() {
$(YOUR_TEXTFIELD_ELEMENT).html(
'<input type="text" value="'+ YOUR_CALCULATION_RESULT
+'" class="field left" readonly="readonly" >');
});
});

How to use jquery to add numbers to input ID name

I am using a wordpress plugin that is generating a input field with a given ID name - fieldname15_6
Im using the code in a loop though so for each post it is creating that input field with the same ID name. Of course this is a problem. I have about 10 inputs with the same ID name and I believe it's causing issues with the display. The font sizes and spacing seems a little random regardless of my CSS rules.
Any how, I need a way to automatically add numbers 1+ to any of the created inputs with that ID name. I tried using the following code but it does nothing --
$("input[id^='fieldname15_6']").attr('id', function (i) {
return "fieldname15_6" + ++i;
});
What am I doing wrong?
Thanks.
var i = 1;
$("input#fieldname15_6").each(function(){
$(this).attr('id', function(i) {
return "fieldname15_6" + ++i;
});
});
This will help you.....
$("input[id^='fieldname15_6']").each(function(i){
$(this).attr('id', $(this).attr('id') + i);
});
Try this:
var $files = $('body').find("input").attr("id","fieldname15_6");
$files.each(function(index)
{
newIndex = $(this).attr("id") + index;
$(this).attr("class", newIndex );
});
The simple answer is Don't. You should use classes for this type of thing, that's what they are for. Then you can use various methods to target and work with the individual elements like .eq()
$('#result').html($('.fieldname15_6').eq(2).val()); // eq is 0 based array syntax so 2 will be the 3rd element
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="fieldname15_6" value="first value">
<input type="text" class="fieldname15_6" value="second value">
<input type="text" class="fieldname15_6" value="third value">
<br>
<br>
<br>
<br>
<div id="result"></div>

Updated HTML from JavaScript variable

im trying to build a form with a few number type inputs that the users picks and one checkbox.
im not using php its all java cause im trying to count a bill using his inputs and print out the result.
how do i print those variables? document.write wont do cause its immidetly prints the var without the calculation.
here is some of the script (which is nothing):
$(document).ready(function(e) {
$('.content_window').css('height','900');
$('#top').css('float','none');
var shutter_price
shutter_price = ($('#shutter').val())*200;
if (shutter != '0' )
write(shutter_price);
});
and the form's input:
<label for="shutter">shutter </label>
<input style="margin-right:98px" name="shutter" type="number" id="shutter">
any suggestions?
Instead of document.write it would be better to update or add an element on the page.
For example, modifying your provided code and markup:
Javascript (jQuery)
$(document).ready(function(e) {
$('.content_window').css('height','900');
$('#top').css('float','none');
$('#shutter').on("change", function(e) {
var shutter_price = $(this).val()*200;
if (shutter_price >= 0) {
$('#shutter-result').text(shutter_price);
}
});
});
HTML
<label for="shutter">shutter </label>
<input style="margin-right:98px" name="shutter" type="number" id="shutter" min="0" step="1" pattern="\d+" />
<div id="shutter-result"></div>
JSFiddle
I think you can create a div on your HTML,
and use: $('#id_of_div_where_you_want_to_write').html("text you want to write");
p.s. This is javascript
javascript != java o/
Hope it helps bro!
i've typed the whole calculation.
i have a submmision button which by clicking needs to retrive the sum.
it doesnt work... im pretty new at javascript so i cant really tell where is the problem.
here is the code:
$('#home_price').submit(function(){
var shutter_price, lights_price, socket_price, screen10_price, screen7_price, dimmer_price, x
var total_price = 3000;
shutter_price = ($('#shutter').val())*200;
light_price = ($('#lights').val())*200;
socket_price = ($('#socket').val())*200;
screen10_price = ($('#screen10').val())*700;
screen7_price = ($('#screen7').val())*200;
dimmer_price = ($('#dimmer').val())*400;
if($('#boiler').is(":checked")==true){
total_price+=600;
x+=1;
}
x+=($('#shutter').val())*2+($('#lights').val())+($('#socket').val());
Math.floor(x);
x+=1;
total_price = total_price + shutter_price + light_price + socket_price + screen10_price + screen7_price + dimmer_price + x*400;
$('#home_pricing').val()=total_price;
if($('#home_pricing').val() < 6000)
alert('the solution invalid');
else
alert(" total: " + $('#home_pricing').val());
});
});
and a piece of the html code:
<label for="screen7"> 7inch screen </label>
<input style="margin-right:70px" name="screen7" type="number" id="screen7"> <br><br>
<label for="dimmer"> dimmer</label>
<input style="margin-right:174px" name="dimmer" type="number" id="dimmer"> <br><br>
<label for="boiler"> bolier </label>
<input style="margin-right:148px" type="checkbox" name="boiler" id="boiler" > <br><br>
<div>
<input type="submit" name=" home_pricing " id="home_pricing" value=" calculate " >
</div>
</form>
any suggestion of how to make the computation and retrive an alert window or other sort of window with the answer?
tnx
I know you did not say that you are using jquery, but I would highly recommenced it, because it makes javascript a lot easier. If you need to display this value to the user then you can use jquery's html function. Here is the link, https://api.jquery.com/html/. I would just write the value to a div that's is suppose to display the answer.
Let me know if you need it, and I can give you a quick plunker.

Use RegEx and .replace to substitute text with user input?

I'm new to jQuery and stumbled on the concept of RegEx with .replace to make nifty text replacements.
In my form, I have some checkboxes that trigger text to appear in a textarea. There are also some user input areas as fields.
How can I use this jQuery to substitute a portion of text in certain checkboxes with the user input, but not in others? I figure using an if/else argument to trigger the RegEx and replace is key, but I don't know how to incorporate the rest?
Here is a mockup of my form:
<div style="width: 500px;"><br>
Static options:<br>
<label id="_comLine100"><input id="comLine100" name="comLines" type="checkbox"> OPTION1 </label> <br>
<label id="_comLine101"><input id="comLine101" name="comLines" type="checkbox"> OPTION2 </label> <br>
Options which can be modified by user text:<br>
<label id="_comLine102"><input id="comLine102" name="comLines" type="checkbox"> OPTION3 </label> <br>
<label id="_comLine103"><input id="comLine103" name="comLines" type="checkbox"> OPTION4</label> <br>
</div>
<br>
<input id="usrinput1" size="50" placeholder="Enter something to replace the word Text">
<br><br>
<form>
<input onclick="javascript:this.form.outPut2.focus();this.form.outPut2.select();"
value="Select all" type="button">
EDIT Here is my new script, based on suggestions below:
$(document).ready(function(){
var comLines = {
comLine100: 'Text for option1 \n',
comLine101: 'Text for option2 \n',
comLine102: 'Text for option3 \n',
comLine103: 'Text for option4 \n'
};
var mytextbox = document.getElementById('outPut2');
var chosenComm = null;
var Inputs = document.getElementsByName("comLines");
for (var i = 0; i < Inputs.length; i++) {
Inputs[i].onchange = function() {
chosenComm = this;
printComment();
};
}
function printComment(){
if(chosenComm !== null){
var chxbox=chosenComm.id;
var uinput = document.getElementById('usrinput1');
if(uinput.value!=="" && (chxbox=="comLine102" || chxbox=="comLine103")){
mytextbox.value += comLines[chosenComm.id].replace(/Text/, $('#usrinput1').val()) + "\n";
// resets the radio box values after output is displayed
chosenComm.checked = false;
// resets these variables to the null state
chosenComm = null;
}
else {
mytextbox.value += comLines[chosenComm.id] + "\n";
// resets the radio box values after output is displayed
chosenComm.checked = false;
// resets these variables to the null state
chosenComm = null;
}
}
}
});
See my JSfiddle : http://jsfiddle.net/bENAY/2/
Now works as I wanted. Thanks to Eric S for the explanations and guidance!
The simple answer is replace:
mytextbox.value += comLines[chosenComm.id] + "\n";
with
mytextbox.value += comLines[chosenComm.id].replace(/Text/, $('#usrinput1').val()) + "\n";
The replace call looks for the regex in the slashes and replaces the match with the value after the comma.
$('#usrinput1').val() is using jQuery to find the dom element with ID of usrinput1 and then getting the value of it (since it's an input, it gets whatever the user has entered).
The more complete answer would mention that you probably should embrace jQuery more:
Replace the window.onload call with a $(document).ready(function(){...}) call.
Consider replacing the document.getElementById with $('#outPut2')
Consider replacing the document.getElementsByName with $(input[name=commLines]) or adding a class of comm-lines to all of those items and using $(.comm-lines)
Consider using jQuery's on function to bind the event handlers for both the inline button handlers (use a passed in function to the on call) and the Inputs[i].onchange calls.
Sorry if this sounds overly judgmental, just trying to suggest a more standard and less error-prone solution.
Still requires some tweaking, but something along the lines of this:
$('.comm-lines').on('change', printComment);
Also, I'm sure this is just a simplified example of what you're trying to accomplish, but you might consider using links or buttons instead of checkboxes. Your use of checkboxes doesn't really follow the expected experience your users have learned when using checkboxes on the web. A link more closely matches the experience most users know, and so provides less surprise to them. (Less surprise means happier users, less learning on their part and more usage.)

jQuery - How to write text values to a hidden field for later use?

I am using the latest and greatest jQuery.
I have a form with three text fields and three hidden fields. When you type in a text field, the value will be passed into the respective hidden field, which will later be accessed by other means.
FirstName value should be passed to FirstNameTemp
LastName value should be passed to LastNameTemp
Pseudonym value should be passed to PseudonymTemp
The following code is not working for me, though I swear it was working yesterday. I am using FireFox and Firebug. I can watch the value of FirstNameTemp change, which seems to work fine in the code, but nothing else works property.
Is there anything wrong with this? Am I missing something obvious?
<input type='hidden' value="" id="FirstNameTemp">
<input type='hidden' value="" id="LastNameTemp">
<input type='hidden' value="" id="PseudonymTemp">
<input type='text' value="" class="Search" id="FirstName"><br>
<input type='text' value="" class="Search" id="LastName"><br>
<input type='text' value="" class="Search" id="Pseudonym"><br>
<script type="text/javascript">
$(document).ready(function() {
$(".Search").keyup(function() {
var FirstName = $("#FirstName").val();
var LastName = $("#LastName").val();
var Pseudonym = $("#Pseudonym").val();
// COPY ENTITIES TO TEMP ENTITIES
$("#FirstNameTemp").val(FirstName);
$("#LastNameTemp").val(LastName);
$("#PseudonymTemp").val(Pseudonym);
});
});
EDIT
I opened and closed my browser and rebooted my machine. Nothing worked. So, I downloaded Firefox and FireBug and reinstalled. It worked just fine.
Thanks to all of you for the help and good ideas. You guys ROCK!!!
Why not do it like this:
$(".Search").keyup(function() {
$('#'+this.id+'Temp').val($(this).val());
});
Fiddle: http://jsfiddle.net/each/mtFt6/
try this..
$(document).ready(function() {
$(".Search").keyup(function() {
var targetId = "#" + $(this).attr("id") + "Temp";
$(targetId).val($(this).val());
});
});

Categories

Resources