Javascript text input (+checkbox options) and text output to easily Ctrl + C - javascript

The closest existing thread I could find on here is this one:
How can I output multiple text fields to one page
And it's a similar idea. Basically my objective is to allow for multiple inputs (text, checkboxes, etc) and then output into a simple text field that is preferably automatically copied to one's clipboard but it doesn't have to be that fancy, as long as it can easily be copied and pasted elsewhere.
Background:
At work, we have a naming convention we use for creating contracts and they follow the same sort of format but if we can easily punch in the same fields and check off certain products to then output text to copy and paste, it would make life SO much easier.
I was working off those input your name and then it outputs a "Hi whatever you inputed!" scripts and also looking into mad lib javascripts because they are kind of the same idea minus the checkboxes... but I am stuck. I am a javascript newbie so I am not sure how to properly incorporate multiple textboxes and checkbox options to output into one line of text (that would be great to have a feature similar to those coupon sites like retailmenot where you just click into it and it automatically Ctrl + C it for you)
So using the above as a starting point, my idea is that
1) Where it says Type your Name (text box), it would have about 5 of those fields
2) 4 sets of multiple checkbox options with the last checkbox a text field that is equivalent to "other"
3) Then once the button is clicked, I would like it to output a certain text string based on the above fields that the user has inputed in the textbox and the checkbox options that had been checked (including adding in the "other" field if applicable) that links all these inputs together in a way that looks like (text1)(text2)(text3)_etc
Are there any existing code, links to tutorials for this or instructions on how I can modify the example javascript to accomplish something like this? Note: I am a javascript newbie
thanks!

I created this simple script a while back. Is this what you are after?
Working Fiddle
html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
First Name :
<input type="text" name="fName" />
<br>Last Name :
<input type="text" name="lName" />
<br>Gender :
<input type="radio" name="gender" value="male" />Male
<input type="radio" name="gender" value="female" />Female
<br>Occupation :
<select name="occ">
<option value="carpenter">Carpenter</option>
<option value="engineer">Engineer</option>
<option value="doctor">Doctor</option>
</select>
<br>Pref :
<input type="checkbox" name="one" />One
<input type="checkbox" name="two" />Two
<br>
<textarea id="result"></textarea>
<br>
<button id="submitBtn">Submit</button>
<div id="message" style="color:red"></div>
jquery
$("#submitBtn").click(function () {
var firstName = $("input[name=fName]").val();
var latName = $("input[name=lName]").val();
var gender = $("input[name=gender]:checked").val();
var occ = $("select[name=occ]").val();
var pref1 = $("input[name=one]").is(":checked");
var pref2 = $("input[name=two]").is(":checked");
$("#result").val(firstName + " " + latName + " " + gender + " " + occ + " " + pref1 + " " + pref2);
$('#result').focus(function () {
this.select();
document.execCommand("copy");
$("#message").html("Text copied to clipboard!");
}).mouseup(function () {
return false;
});
$('#result').focus();
});

Related

JavaScript only changes text of first iteration with thymeleaf

I hope you are all well.
I have a school assignment, and I want to dynamically be able to change the name of a 'project'. This assignment is about projects. The way I've done it right now works with the first 'project' from a list of 'projects' iterated through with thymeleaf. I'm aware that what I've done right now is absolutely bad code behavior, but we have had no teaching in JS yet. But I really wanted this feature.
I don't know how to make this work for each project preview, right now it works for the first preview, but for the rest it just erases the project name from database. (see picture)
<div class="projects" th:each="projectNames : ${listOfProjects}">
<form action="deleteProjectPost" method="post">
<input type="hidden" th:value="${projectNames.projectID}" name="deleteID">
<input type="image" src="delete.png" alt="Submit" align="right" class="deleteProject" onclick="return confirm('Are you sure that you want to delete this project?')">
</form>
<form action="/editProjName" method="post">
<input type="hidden" name="projectID" th:value="${projectNames.projectID}">
<input type="hidden" id="oldName" th:value="${projectNames.projectName}">
<input type="hidden" id="newName" name="projectName">
<input type="image" src="edit.png" alt="Submit" onclick="change_text()" align="right" class="editProject">
</form>
<form action="/projectPost" method="post">
<input class="projectInfo" name="projectID" type="text" th:value="'Project No.: ' + ${projectNames.projectID}" readonly="readonly">
<input class="projectInfo" type="text" th:value="'Project name: ' + ${projectNames.projectName}" readonly="readonly">
<input class="projectInfo" type="text" th:value="${projectNames.projectStartDate} + ' - ' + ${projectNames.projectEndDate}" readonly="readonly">
<input type="submit" value="OPEN" class="openProject">
</form>
</div>
<script>
function change_text() {
var changedText;
var projectName = prompt("Please enter name of project:");
var oldName = document.getElementById("oldName").value;
if (projectName === null || projectName === "") {
changedText = oldName;
} else {
changedText = projectName;
}
document.getElementById("newName").value = changedText;
}
</script>
First form in HTML is the red cross to delete an entire 'project'. Second form is what is intended to change the name displayed on the 'project preview', but only works on first preview and deletes project name from the rest. Last form is the actual preview. I couldn't find another way to have multiple forms and do different POSTS while working with Java Spring and Thymeleaf.
My wish is to make the change_text() function work for each 'project preview'
Best regards!
function change_text(imageInput) {
var changedText;
var projectName = prompt("Please enter name of project:");
var oldName = imageInput.parentNode.querySelector('.old-name').value;
if (projectName === null || projectName === "") {
changedText = oldName;
} else {
changedText = projectName;
}
imageInput.parentNode.querySelector('.new-name').value = changedText;
}
<form action="/editProjName" method="post">
<input type="hidden" name="projectID" th:value="${projectNames.projectID}">
<input type="hidden" class="old-name" id="oldName" th:value="${projectNames.projectName}">
<input type="hidden" class="new-name" id="newName" name="projectName">
<input type="image" src="edit.png" alt="Submit" onclick="change_text(this)" align="right" class="editProject">
</form>
Ok so I made a few changes. First, notice the inputs with oldName and newName now have classes on them. These can be repeated. If you are not using the ids for anything other than the script, you should remove them. Otherwise if you have styling rules for them you should consider changing those CSS rules to use the class instead so you can remove the invalid repeating ids.
Secondly, the onlick of the image now passes in this. What that does is it passes in the actual input that the user clicked, so you have some context into which form element the user is interacting with.
Then looking at the logic, the method now accepts in imageInput which is the this from the onclick.
Using imageInput.parentNode we go up the DOM Tree to the parent element of the input, which is the form in this case. We can then turn around and use querySelector to find the other element in the form we want to manipulate. And it will only find the element in our particular form because that is what we are selecting off of.

Running clone n number of times

i'm currently using this code to clone a text input field when clicking on a button with the id btnAdd
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length;
var newNum = new Number(num + 1);
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
$('#input' + num).after(newElem);
$('#btnDel').attr('disabled','');
if (newNum == 25)
$('#btnAdd').attr('disabled','disabled');
});
What i want to do is be able to press another button and have it add a certain number of cloned text fields, while still renaming the ids to name + n
I want to do this so i can have a button create fx. 5 text fields and then populate them with predetermined values.
Right now i have to first create 4 textfields for 5 total, and then call the function with another button, to alter the text fields.
A point in the right direction would be appreciated.
Example i used in comments:
Let’s say that i want to have a site where you can input a list of names
I start with one input boxes
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
<input type="text" name="name1" id="name1" placeholder="Port" />
</div>
Then i want the user to be able to add more input boxes. so i use the clone code in the OP
This enables the user to manually add all the names they want.
But i want to be able to have the user be able to choose from pre selected lists, lets say a list of all the names of the football team.
So i want the user to be able to press a button, which creates fx. 11 input boxes, and then fills out the boxes with all the 11 names of the football team.
To do this i have been using this code:
function Input() {
$('#name1').val(‘John’)
$('#name2').val(’Steve’)
$('#name3').val(‘Maria’)
$('#name4').val(‘Ida’)
}
But if the user has not created enough clones of the input boxes, this just fills out the created ones.
I hope I understood the behaviour you wanted. It basically adds inputs in the div block you want with some random names as value.
var names = ["Chris", "Jimmy", "George", "Martin", "Keith"];
function createInputs(numberOfInputs, blockId) {
var i = 0;
var inputBlock = $("#" + blockId);
inputBlock.empty();
while(i < numberOfInputs && i < names.length) {
inputBlock.append($('<input type="text" name="name" id="name'+ i + '"/>').val(names[i]));
i++;
}
}
input {
display: block;
margin: 5px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button onclick="createInputs(3, 'input1')">Create 3 random inputs</button>
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
<input type="text" name="name1" id="name1" placeholder="Port" />
</div>
<button onclick="createInputs(5, 'input2')">Create 5 random inputs</button>
<div id="input2" style="margin-bottom:4px;" class="clonedInput">
<input type="text" name="name1" id="name1" placeholder="Port" />
</div>

HTML/Javascript Input type="text" - How to shows text different from value?

Actually i have a datalist:
<datalist id='modelsList'>
<option value='1'>Dummy1</option>
<option value='2'>Dummy2</option>
</datalist>
This is used in an input:
<input type='text' name='dummy' autocomplete='off' list='modelsList' value=''/>
If i start typing Dummy2 and then i click on the dropdown list result the textbox shows 2. I need to find a way to have 2 as value but Dummy2 as text.
I cannot use a drop-down list (select tag)
Here, my solution as per you want check it out...
You can use input event for achieving such functionality,
HTML
<input type='text' id='dummy' list='modelsList'/>
<datalist id='modelsList'>
<option value='1'>Dummy1</option>
<option value='2'>Dummy2</option>
</datalist>
Jquery
$("#dummy").on('input', function () {
var val = this.value;
if($('#modelsList option').filter(function(){
return this.value === val;
}).length) {
var option = $('#modelsList').find('option[value="' + val + '"]');
$(this).val(option.text());
}
});
also check DEMO of the above code.
The format for a text input in HTML5 is as follows:
<input type="text" name="name" value="Value" placeholder="Placeholder Text">
As a user types in their content, the value changes.
You may be getting confused with textarea:
<textarea name="name">Value</textarea>
If you want to put a textarea tag, you have to know that the value attribute is invalid, but perhaps if you want to use it instead of input, and the format is similar as you put:
<textarea name="name">contentHere</textarea>

selecting text next to an checked input checkbox using JQuery (or JS)?

given the next HTML block:
<div class"radioGroup">
<input type="radio" value="0">
This is NOT checked
<input type="radio" value="1" checked = "checked" >
This is checked
<input type="radio" value="2">
This is NOT checked
</div>
How can i select the text following the selected radio button? (e.g "This is checked").
(I cant add tags to the strings or something like that, i'm trying to grab this text from another web page, so i can only use client side scripts)
You can use:
<input ... onclick="alert(this.nextSibling.data);">
Of course that is very dependent on the structure of the DOM. You may want to concatenate the data in all the text nodes from this element to the next, so you might need a function like:
function getTextByNodes(el) {
var text ='';
while (el && el.nextSibling && el.nextSibling.nodeType == 3) {
text += el.nextSibling.data;
el = el.nextSibling;
}
return text;
}
with:
<input ... onclick="alert(getTextByNodes(this));">

Issue with processing form i ajax with radio buttons

I have this script which makes possible the insertion of some data using ajax and php.
Now , all works fine, except the radio buttons (the select options work fine as well) , and it takes the first value of the radio buttons..
Why is this happening?
Here is the code:
<div id="formfields" ><label>Tipologia Pdv: </label>
<input type="radio" name="tipologia_pdv" id="tipologia_pdv" value="Iper" style="width:40px;" /><span > Iper</span>
<input type="radio" name="tipologia_pdv" id="tipologia_pdv"
value="Super" style="width:40px;" /><span > Super</span><br /><br /></div>
<div id="formfields" ><label>Richiesta Ccnl: </label>
<input type="radio" name="richiesta_ccnl" id="richiesta_ccnl" value="Si" style="width:40px;"/><span> Si</span>
<input type="radio" name="richiesta_ccnl" id="richiesta_ccnl"
value="No" style="width:40px;"/><span> No</span><br /><br /></div>
The javascript:
// Fetch data from input fields.
var js_tipologia_pdv = $("#tipologia_pdv").val();
var js_richiesta_ccnl = $("#richiesta_ccnl").val();
//let's put all data together
var myData = 'postTipologia_pdv='+ js_tipologia_pdv + '&postRichiesta_ccnl='+ js_richiesta_ccnl + '&postDistretto_pdv=' + js_distretto_pdv + '&postCoopva_pdv=' + js_coopva_pdv + '&postNome_pdv=' + js_nome_pdv;
In php they go something like this:
$postTipologia_pdv = filter_var($_POST["postTipologia_pdv"], FILTER_SANITIZE_STRING);
$postRichiesta_ccnl = filter_var($_POST["postRichiesta_ccnl"], FILTER_SANITIZE_STRING);
Making my comments into an answer:
1) Your id attributes need to be unique.
2) Get the value of the selected radio button using something like: $('input:radio[name=tipologia_pdv]:checked').val();

Categories