jQuery toggle - Changing from select input to text input - javascript

I'm very new to using jQuery and JavaScript but here goes. I am trying to create a toggle function for my website. There is an input to select the name of the event which displays as default as a dropdown list of all the events in the database - but I want there to be an option to change it to manual input and type the name of the event as what ever you want.
I can get this to work fine! However I can't get the link to change the input BACK to a select box to work.
See my code below:
/// jQuery Code ///
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
function toggleEventInput() {
$("#EventNameDropDown")
.replaceWith('<input type="text" size="35" name="boxEvent" class="FieldInput" />');
$("#EventNameChange")
.replaceWith(' (Drop Down Input)');
}
function toggleEventInputBack() {
$("#EventNameDropDown")
.replaceWith('TEST');
$("#EventNameChange")
.replaceWith(' (Manual Input)');
}
</script>
/// HTML Code ///
<table>
<tr>
<td class="label">Event:</td>
<td>
<span id="EventNameDropDown">
<select name="boxEvent" class="FieldInput" style="width:254px;" />
<?= $EventNameDropDownList ?>
</select>
</span>
<span id="EventNameChange">
(Manual Input)
</span>
</td>
</tr>
<tr>
<td class="label">Company:</td>
<td><input type="text" size="35" name="boxEvent" class="FieldInput" /></td>
</tr>
</table>
As said, when you click the original link to '(Manual Input)' it works fine and changes it to a text box. But then when you click the '(Drop Down Input)' link it does nothing.
Any help would be appreciated.

You need to use .html() instead of .replaceWith(). The former replaces the contents of the element. The latter replaces the element itself. By using .replaceWith() you are replacing the <span> that contains the <select> too.
Krishna is suggesting that rather than just replace the html for the <select>, you first store it in a variable so you can put it back later.
You could store it as data on an element, like this:
function toggleEventInput() {
// Store the html for the <select>.
$('#EventNameDropDown').data('selectHtml', $('#EventNameDropDown').html());
$("#EventNameDropDown").html('<input type="text" size="35" name="boxEvent" class="FieldInput" />');
$("#EventNameChange").html(' (Drop Down Input)');
}
function toggleEventInputBack() {
$("#EventNameDropDown").html($('#EventNameDropDown').data('selectHtml'));
$("#EventNameChange").html(' (Manual Input)');
// Clear the html for the <select>. We will get it again later if we need it.
$('#EventNameDropDown').data('selectHtml', '');
}

Its better to add the drop-down list inside a div/span and while clicking the toggle button, store the data inside the div/span to a variable and replace the content with the input box. on next toggle, replace the div/span with that data in the variable. a status variable 0/1 will help to toggle the data..

Related

How can I edit table row using JavaScript querySelector()?

I am trying to edit data from a table. When the edit button is pressed it will bring up an input field to edit the new value in the selected row, I tried using the code below, but nothing changes when I press the edit button.
Here is my code:
const editRow = (index = "x") => {
const tdTable = document.querySelectorAll("table > tbody > tr");
const newRow = `
<tr>
<td>
<input type="text" name="name" />
</td>
<td>
<input type="text" name="umur" />
</td>
<td>
<input type="text" name="address" />
</td>
<td colspan = 2>
<span class="btn btn-info" onClick="saveData()">Save</span>
</td>
</tr>`;
tdTable.innerHTML = newRow;
};
Here is what the table looks like in the browser when I press the edit button.
You need to do something to actually put the input values back into the original <td>s. Below I prepared an MCVE (minimal complete and viable example), showing how it can be done:
const tb=document.querySelector("tbody"), edidel="<button>Edit</button> <button>Delete</button>";
// prepare the page first (fill in some sample data):
tb.innerHTML= [[1,"jansen",35,"medan"],
[2,"Alfa",31,"jakarta"],
[3,"joko",10,"solo"],
[4,"eko cahyonto",20,"NTB"]].map(r=>
"<tr><td>"+r.join("</td><td>")+"</td><td>"+edidel+"</td></tr>" ).join("\n");
tb.onclick=ev=>{
[...ev.target.closest("tr").children].forEach((td,i)=>{ const btn=ev.target.textContent;
if (btn==="Edit")
td.innerHTML=i<4?'<input type="text" value="'+td.textContent+'" data-orig="'+td.textContent+'">'
:'<button>Save</button> <button>Cancel</button>';
else if (["Save","Cancel"].includes(btn))
td.innerHTML=i<4?(btn==="Save"?td.children[0].value:td.children[0].dataset.orig)
:edidel;
})
}
input {width:50px}
<table>
<thead><tr><th>No</th><th>Nama</th><th>Umur</th><th>Alamat</th><th>CRUD</th></thead>
<tbody></tbody>
</table>
The first 7 lines of code simply prepare a small table on which we can work. The actual script then starts with a "delegated click event attachment" on the first <tbody> element of the page (which happens to be our test table). This means, we can add or remove table records and don't have to worry about attaching events to the newly created buton elements any more.
An action will only happen, if the clicked element has an ยด.textContent` of either "Edit", "Save" or "Cancel" (an action for the "Delete" button has not yet been defined but can easily be added).
Depending on the actual clicked button some action on the <TD> elements directly before the button will be performed:
when going into "Edit"-mode the td.textContent of each <td> is copied into a newly created <input type="text"> element and is also save in its data-orig attribute, in case we want to click on "Cancel" later on.
"Save" will copy the .value of each <td>s first child (the <input> element) back to its parent td.innerHTML attribute.
in case "Cancel" was clicked, the <input>'s .dataset.orig value is put back into the td.innerHTML attribute.
JavaScript is a case-sensitive language.
try fixing the uppercase onClick to onclick, as the example: <button onclick="myFunction()">Click me</button>

Find element that appears after a specific element in a separate <td>

I first use this code to find an element with a specific text content:
$('someElement').filter(function() {
return $(this).text() == 'Some text';
});
Then, I want to find the <input> element that's inside the next <td> tag.
Below is the HTML code:
<tr>
<td>
<label for="SH_Request_First_Name">
First name <span class="required">*</span>
</label>
</td>
<td colspan="2">
<input type="text" name="SH_Request_First_Name" id="SH_Request_First_Name"
value="" size="38" maxlength="50" onchange="validatePresent(this, 'SH_Request_First_Name_Note');"
/> <span id="SH_Request_First_Name_Note"> </span>
</td>
</tr>
I first found the label with text "First name". Then I want to find the <input> that's in the next <td> tag.
Is it possible to do the above tasks in JavaScript, instead of jQuery?
When you've found the first td tag you can access the next one in JS with
yourTd.nextSibling
This will return the next tag in the document.
If you want to get there from the label you first have to get the parent and then the sibling:
yourLabel.parentElement.nextSibling
but this construct is error prone if you change the HTML construct some times. I would recommend to use jQuery and select by a specidic css class or something like that, so it doesn't have to be exactly the next element, only one of the next elements with that css class.

How can I update an element attribute with a modified value?

I am working with MachForm and in it when using pricing features it adds this to an li tag:
<li id="li_273" data-pricefield="text" data-pricevalue="8.48" >
The form also has this field as well:
<input type="text" class="element text medium" id="element_273" name="element_273" size="30" value="" />
Now what happens is, the form has been converted to an ajax auto complete which is fine and works. But the problem is that the first reference:
<li id="li_273" data-pricefield="text" data-pricevalue="8.48" >
Isn't going to be the right price for the item selected. So what I need is to be able to re-write that data-pricevalue based on an onclick function. In the autocomplete you are able to execute an onclick javascript command like so:
'onclick' => 'alert(\'You clicked on the '.$name.' fruit!\');',
Now I have the rest of the javascript that should allow me to take the data-pricevalue from the id (ex: id="li_273") and then multiple it by the value entered into the text box. The ultimate goal is to get data-pricevalue * input text to update the on-screen total value. But I am not sure how to get that data-pricevalue to re-write the proper price.

Copy HTML into textarea on submit

I have a form with multiple blocks of inputs with default values assigned by PHP, and I would like to pass the HTML markup of one of the blocks into a PHP script. Here is a modified snippet of my form to exemplify the markup:
<form action="/page/do_work/job_number" id="work_form">
<textarea style="display: none;" name="markup" id="markup"></textarea>
<div id="block_1">
<table>
<tr>
<td><input type="text" value="123" /></td>
<td><input type="text" value="123" /></td>
</tr>
</table>
</div>
<div id="block_2">
<table>
<tr>
<td><input type="text" value="abc" /></td>
<td><input type="text" value="abc" /></td>
</tr>
</table>
</div>
</form>
I am listening for the submission of the form with some jQuery, so that I can copy the HTML of the table into the textarea.:
$('#work_form').submit(function(){
// Snatch the markup
var markup = $('#block_1', '#work_form').html();
// Place it into the textarea
$('#markup', '#work_form').html( markup );
// Move on
return true;
});
The Problem is that the modified values are not being copied into the textarea. For instance, if I were to change the values from "abc" to "xyz" the markup that is passed to the textarea still says "abc". Any help would be greatly appreciated.
Edit: Using .html() or .val() both add the markup in to the textarea, but I would like to know why the changes in value of the inputs are not reflected in the markup that is inserted into the textarea. Upon further inspection, changing the value of the input fields and then inspectigating them in Firebug shows the default value is retained. Do I need to update the DOM in some way?
Edit 2: The markup variable is being set, but the changes I make to the input fields are not reflected in the markup inserted into the textarea.
Try,
$('#markup', '#work_form').val( markup );
Also throw in a console.log(markup) to make sure the markup variable is getting set right.
Well for text area you need to change its 'value' not its 'innerhtml' and thats what .html does.
$('#markup').val(markup)
Try this.
Changes to input fields do not change the DOM, which is what I was supposed to do. To change the DOM, I edited the .submit() function to look like this:
$('#work_form').submit(function(){
// Update the DOM
var block_1 = $('#block_1', '#work_form');
block_1.find('input').each(function(i,e){
el = $(e);
el.attr('value', el.val());
});
// Snatch the markup
var markup = block_1.html();
// Place it into the textarea
$('#markup', '#work_form').html( markup );
// Move on
return true;
});
Thanks #PherricOxide for pointing me to this question:
reading innerHTML of HTML form with VALUE attribute (& its value) of INPUT tags

sending the elements of a select form to another one

it's my first post here and I so sorry if I wrong the place.
My difficulty is view the elements of the first select form to the other one if the first form is set as array.
The goal is to send the elements of a select form to another one and then record them on a db MySQL, that will show them on a html page.
I found in this forum the procedure how to create two select form and add 'n remove the items, then with the command .implode of MySQL can join the element and insert multiple items on db and view them on page.
But if I set the name's select form as array it doesn't work. I've used the following script to have two select form :
<script language="javascript">
function getOpt(select1,select2)
{
for (bCnt=0;bCnt<select1.length;bCnt++)
{
if (select1.options[bCnt].selected)
{
newOpt=new
Option(select1.options[bCnt].text,select1.options[bCnt].value,false,false);
select2.options[select2.length]=newOpt;
}
}
}
function remOpt(select2)
{
for (bCnt=0;bCnt<select2.length;bCnt++)
{
if (select2.options[bCnt].selected)
select2.options[bCnt]=null;
}
}
</script>
then the selects form:
<table border="0">
<tr>
<td>
<label for="id">List:<br></label>
<select name="oneS" id="select_role" size=20 required multiple="multiple"/>
<option value="101">101</option>
<option value="102">102</option>
<option value="103">103</option>
<option value="104">104</option>
<option value="105">105</option>
<option value="106">106</option>
</select>
</td>
<td>
<input type="button" value="Add"onClick="getOpt(this.form.oneS,this.for m.twoS)"><br>
<input type="button" value="Remove"onClick="remOpt(this.form.twoS)">
</td>
<td>
<label for="id">Members List:<br></label>
<select name="twoS" id="select_role" size=20 multiple="multiple"/>
</select>
</td>
</tr>
</table>
if comment the script,the part of the buttons, the second form and change the line:
<select name="oneS" id="select_role" size=20 required multiple="multiple"/>
in
<select name="oneS[]" id="select_role" size=20 required multiple="multiple"/>
I have any issue, can record the items of the first select form on db and view them on the page.
But it's not my goal, I've have to use 2 select form.
Is there some one can help me? thanks a lot.
I've you use jQuery, here it is:
$(document).ready(function()
{
$('.add').click(function(event)//this is your first form, with the id "select_role"
{
$('#select_role2).html($(this).html()+"add whatever html code you want to insert into here");
});
});
use the same idea for remove item.
then use an $.ajax or $.post to send the data to mysql or use a variable to store all the html that was added or removed from your second select.
Simply include the jQuery library and you are all sorted. I have not written raw JAvascript in a long long time, but this will work with the help of jQuery. don't use the same id for two elements again. The id must be unique.
Then assuming you insert a whole bunch of options, you can use $('#your_form_id).serialize() within an $.ajax call to get the array of elements then use the PHP technique for parsing name="insertedoption[]" />. I'm not completely sure I helped you too much, as you need to read up on a few things, but this is an idea on how to do what you need to do.

Categories